在范围中使用列号而不是A1?

时间:2013-12-12 14:56:05

标签: excel vba excel-vba excel-2010

我有这个子作用于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表示法逐步遍历列的方法吗?

如果这是一个愚蠢的问题我很抱歉,我在发帖前已经搜索了几天。对初学者表示同情。 :) 谢谢, 卡盘

@Siddarth,非常感谢,你的代码让我朝着正确的方向前进。使用你的第二个Sub我发现它将所有单元格的值更改为“text”。我有兴趣一次操作一列并修改代码只改变A列,你看到语法有什么问题吗?

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

2 个答案:

答案 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))