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

标签 vba excel excel-2010

我有这个子程序,它作用于 A 列、A1 直到最后一行数据,并将这些单元格中的值更改为“文本”:

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,非常感谢你,你的代码让我朝着正确的方向前进。使用您的第二个子我发现它将所有单元格的值更改为“文本”。我对一次操作一列感兴趣,并修改了代码以仅更改 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

最佳答案

您可以使用列名称/数字,而无需使用 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

关于vba - 在范围中使用列号而不是 A1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546786/

相关文章:

vba - ThisWorkbook.Sheets(1).Select (False) 不起作用

excel - 在excel vba中将字符串转换为二进制

java - Excel 单元格中的值为空?

excel - 基于一列值的 Excel VBA 过滤表

regex - VBA 正则表达式替换代码

html - 如何使用 VBA 从嵌套 div 中提取值

excel - 忽略 Excel 折线图上的单元格

vba - 简单的VBA选择: Selecting 5 cells to the right of the active cell

VBA:Msgbox循环,对两个数字之间的值求和,包括

excel - 如何检查单元格的当前值是否在所有先前单元格的某个值之内