首页 > 解决方案 > 使用变量代替列

问题描述

我正在编辑我记录的这段代码,我想知道如何用变量 i 替换 Columns("A:A")

代码是依次选择每一列,从大到小排序。

我正在使用 i 遍历列。问题是我不确定如何将当前引用范围 A1 或范围 A:A 的代码转换为使用列 i。

Sub sort_largest()

Dim i As Long

i = 1 + 1

Do Until Cells(1, i) = ""




Columns("A:A").Select
    ActiveWorkbook.Worksheets("Pivot Tables").Sort.SortFields.clear
    ActiveWorkbook.Worksheets("Pivot Tables").Sort.SortFields.Add Key:=Range("A1" _
        ), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Pivot Tables").Sort
    .SetRange Range("A:A")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

i = i + 1
Loop

End Sub

标签: vbavariables

解决方案


这是使用变量而不是硬编码范围的快速重写:

Sub sort_largest()

    Dim i As Long

    i = 2
    Do Until Cells(1, i) = ""

        ActiveWorkbook.Worksheets("Pivot Tables").Sort.SortFields.clear
        ActiveWorkbook.Worksheets("Pivot Tables").Sort.SortFields.Add Key:=Cells(1, i), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Pivot Tables").Sort
            .SetRange Columns(i)
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With

        i = i + 1
    Loop

End Sub 

最棘手的一点是切换出去,Range("A1")因为循环中的列 variablei是数字的。相反,您可以使用非常方便的对象来引用该范围,该Cells()对象带有两个参数:数字行和数字列。所以Range("A1")是一样的,Cells(1, 1)然后我们可以1用变量交换那一秒。

ps 我没有对此进行测试,所以它可能不是 100%,但我认为它会正常工作。


推荐阅读