在Excel中使用VBAselectdynamic表范围

我试图select一个dynamic表 – 我可以找出脚本的复制/粘贴部分,但我不知道如何最初select这个表。

该表根据行数和列数是dynamic的。 这是因为这个单独的工作簿需要被不同的业务部门使用,调用不同的SQL服务器表。 因此,用户将其input放在Sheet1中,刷新连接,并在Sheet2中返回一个表格。

这里是片段,包括一个工作和一个破碎的部分:

'Variable designations Dim rowcount As String Dim columncount As String Dim sheetref1 As String Dim sheetref2 As String Dim rangeselect1 As String Dim rangeselect2 As String rowcount = Cells(Rows.Count, 1).End(xlUp).Row columncount = Cells(1, Columns.Count).End(xlToLeft).Column sheetref1 = "Sheet1" sheetref2 = "Sheet2" rangeselect1 = "A2:A" & rowcount rangeselect2 = "A1:" & columncount & rowcount '<--BROKEN 'Copy column with populated rows Sheets(sheetref1).Range(rangeselect1).Copy '<--WORKING 'Copy table with populated rows and columns Sheets(sheetref2).Range(rangeselect2).Copy '<--BROKEN 

所以这里rangeselect2 = "A1:" & columncount & rowcount我想返回类似A1:Z10或A1:F3000 – dynamic范围(顺便说一下,A1是静态的)。 我试图为columncount返回“Z”或“F”或任何最后一列字母,而rowcount(希望)正确地返回最后一个行号。

希望这是有道理的。 我会很乐意回答任何进一步的问题,我非常感谢任何build议/帮助。

您的rangeselect2 = "A1:" & columncount & rowcount不起作用,因为columncountrowcount返回为指示行和列的数字。 如果要将columncountrowcount转换为A1地址(例如第2列和第5行是B5 ),则可以使用Cells(rowcount, columncount).Address ,它返回该坐标的绝对引用。

rangeselect2 = "A1:" & Cells(rowcount, columncount).Address应该适用于你在这里要做的事情。

这将find并select所有单元格从A1到包含该代码所在工作簿Sheet1上的数据的最后一个单元格:

 Sub SelectDynamicTable() Dim rFinalRange As Range Dim lLastRow As Long Dim lLastCol As Long With ThisWorkbook.Worksheets("Sheet1") lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row If lLastCol = 0 Then lLastCol = 1 If lLastRow = 0 Then lLastRow = 1 Set rFinalRange = .Range(.Cells(1, 1), .Cells(lLastRow, lLastCol)) End With rFinalRange.Select End Sub 

使用单元格而不是范围 – 单元格可以接受行号和列号,而不是字母指定。

当给定工作表参考和可选列时,此函数将返回对最后一个单元格的引用。

 Public Function LastCell(wrkSht As Worksheet, Optional Col As Long = 0) As Range Dim lLastCol As Long, lLastRow As Long On Error Resume Next With wrkSht If Col = 0 Then lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row Else lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column lLastRow = .Columns(Col).Find("*", , , , xlByColumns, xlPrevious).Row End If If lLastCol = 0 Then lLastCol = 1 If lLastRow = 0 Then lLastRow = 1 Set LastCell = wrkSht.Cells(lLastRow, lLastCol) End With On Error GoTo 0 End Function 

该testing过程将显示activeworkbook第2列中最后一个单元格的地址:

 Public Sub TestLastCell() MsgBox LastCell(ActiveWorkbook.Worksheets("Sheet2"), 2).Address End Sub 

如果你想在代码中find第一个单元格使用xlNext而不是xlPrevious