我有这个子作用于A列,A1到数据的最后一行,并将这些单元格中的值更改为“text”:
Sub Sample()
Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Range("A1:A" & lastRow).Value = "text"
End Sub
有没有办法在Range中使用R1C1表示法而不是A1表示法来定义列?
我希望最终使用一个变量作为列号,并逐步执行多个列执行重复操作,然后停在包含数据的最后一列。
相反,最好保留A1表示法,因为你可以指出一种使用A1表示法逐步遍历列的方法吗?
如果这是一个愚蠢的问题我很抱歉,我在发帖前已经搜索了几天。对初学者表示同情。 :) 谢谢, 卡盘
Sub Sample2()
Dim ws As Worksheet
Dim rng As Range
Dim LastCol As Long, LastRow As Long
Set ws = ThisWorkbook.Sheets("Results")
With ws
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set rng = .Range(.Cells(1), .Cells(LastRow, 1))
Debug.Print rng.Address
rng.Value = "text"
End With
End Sub
随后我命名了一个变量,我希望这个变量可以步骤,而Sub仍然有效:
Sub Sample2A()
Dim ws As Worksheet
Dim rng As Range
Dim LastCol As Long, LastRow As Long
Dim StarttCol As Integer
StarttCol = 1
Set ws = ThisWorkbook.Sheets("Results")
With ws
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set rng = .Range(.Cells(StarttCol), .Cells(LastRow, StarttCol))
Debug.Print rng.Address
rng.Value = "text"
End With
End Sub
答案 0 :(得分:2)
您可以使用列名/数字而无需使用RC表示法。例如
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
Dim LastCol As Long, LastRow As Long
Dim LastColumn As String
Set ws = ThisWorkbook.Sheets("Results")
With ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
'~~> Return column name from number
LastColumn = Split(.Cells(, LastCol).Address, "$")(1)
Set rng = .Range("A1:" & LastColumn & LastRow)
Debug.Print rng.Address
rng.Value = "text"
End With
End Sub
相同的代码也可以写为
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
Dim LastCol As Long, LastRow As Long
Set ws = ThisWorkbook.Sheets("Results")
With ws
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set rng = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
Debug.Print rng.Address
rng.Value = "text"
End With
End Sub
答案 1 :(得分:0)
只需使用单元格指定范围。例如:范围(A1)==范围(单元格(1,1))
像Range(A1:A10)这样的东西是Range(Cells(1,1),Cells(1,10))