vba - 使用变量代替列
问题描述
我正在编辑我记录的这段代码,我想知道如何用变量 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
解决方案
这是使用变量而不是硬编码范围的快速重写:
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%,但我认为它会正常工作。
推荐阅读
- tensorflow - 尝试在 tensorflow 中导入和格式化我自己的数据集时出错
- flutter - 不能在 int time 之前使用 Cupertino timepicker
- oracle - Delphi - Oracle RowID 被 dbGO/ADO 忽略
- dictionary - Tesseract OCR 添加自定义字典
- fortran - 如何使用 MPI 更改 Fortran 中的默认精度?
- java - 井字游戏 10*10 棋盘 - 寻找赢家
- r - R stat_function 中的置信区间
- angular - 角度模板中导入常量的可见性
- sql - 如何在 Postgres 中获取特定列中相似数据值的数字序列?
- flutter - 各边的 ElevatedButton 填充不会修改