4

我正在尝试将 Last column 用于我的范围:WS.range("F2:LastCol" & LastRow).Cells我的 sub 适用于

WS.range("F2:K" & LastRow).Cells但它Last Column是动态的并且不断变化

谢谢

Sub QQ()

Dim LastRow As Long
Dim LastCol As Long
Dim WS As Worksheet
Dim rCell As range

Set WS = Sheets("sheet1")

LastRow = WS.range("F" & WS.Rows.Count).End(xlUp).Row

LastCol = Cells(2, .Columns.Count).End(xlToLeft).Column
'Also tried: LastCol=rgRange.Cells(rgRange.Count).Column 

For Each rCell In WS.range("F2:LastCol" & LastRow).Cells

STUFF 'The stuff works for WS.range("F2:K" & LastRow).Cells

End Sub
4

3 回答 3

4

LastCol 是一个数字,用于指定范围的语法需要一个字母。

您可以找出列号的列字母并将其传递给您的范围定义,如下所示:

Sub DynamicRange()
    Dim startCol As String
    Dim startRow As Long
    Dim lastRow As Long
    Dim lastCol As Long
    Dim myCol As String
    Dim ws As Worksheet
    Dim rng As Range
    Dim cell as Range

    Set ws = ThisWorkbook.Sheets("Sheet1")
    startCol = "F"
    startRow = 2
    lastRow = ws.Range(startCol & ws.Rows.Count).End(xlUp).Row
    lastCol = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column
    myCol = GetColumnLetter(lastCol)

    Set rng = ws.Range(startCol & startRow & ":" & myCol & lastRow)

    For Each cell In rng
       ' do stuff
    Next cell

    ' check the range we've set
    Debug.Print rng.Address

End Sub

Function GetColumnLetter(colNum As Long) As String
    Dim vArr
    vArr = Split(Cells(1, colNum).Address(True, False), "$")
    GetColumnLetter = vArr(0)
End Function
于 2013-06-05T13:39:21.270 回答
1

请尝试以这种方式定义您的循环:

For Each rCell In WS.range(ws.Range("F2"), Ws.Cells(LastRow, LastCol)).Cells

或者它可以通过这个解决方案走更短的路(如果WSActivesheet):

For Each rCell In WS.range("F2", Cells(LastRow, LastCol)).Cells
于 2013-06-05T13:30:21.050 回答
0
    dim wb As Workbook
    dim ws As Worksheet
    Set wb = ThisWorkbook
    Set ws = wb.Sheets("sheet name")    
    Set ListObj = ws.ListObjects("table name")

If ListObj Is Nothing Then
        Set ListObj = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$15:$Q$16"), , xlYes)
        ListObj.Name = "new table"
Else
        lastRow = ListObj.Range.Columns(1).cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

        ListObj.Resize Range("$B$15:W" & lastRow + 2)
End if
于 2018-07-13T08:27:48.330 回答