我正在尝试使用Last列作为我的范围:WS.range("F2:LastCol" & LastRow).Cells
我的子作品
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
答案 0 :(得分: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
答案 1 :(得分:1)
请尝试以这种方式定义循环:
For Each rCell In WS.range(ws.Range("F2"), Ws.Cells(LastRow, LastCol)).Cells
或者使用此解决方案可能会更短(如果WS
为Activesheet
):
For Each rCell In WS.range("F2", Cells(LastRow, LastCol)).Cells
答案 2 :(得分: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