在VBA中查找列并进行排序

问题描述 投票:0回答:1

您好,我正在尝试创建一个宏,以便更容易地对从机器人导出的数据进行排序

问题是由于机器人进行测试的方式,列可以更改位置

许多列是无用的,所以我做了一个宏来隐藏未使用的列,现在我想添加一个宏,按升序排序这些剩余的4列,但我只是无法破解它

到目前为止我有

Dim c As Range

For Each c In Range("A1:BR1").Cells
    If c.Value = "Plate Name (barcode)" Or c.Value = "Measurement Date" Or c.Value = "Measurement profile" Or c.Value = "pH" Or c.Value = "Count" Or c.Value <= 30 Then
    c.EntireColumn.Hidden = False
    Else: c.EntireColumn.Hidden = True
    End If
    Next c
End Sub

除了命名的列之外,其他每列都隐藏了,但在此之后我无法对其进行排序

我试图找到列/选择列和排序但由于某种原因宏似乎运行而不是实际排序

还尝试录制宏,但随着列移动,代码不断定义列以进行排序,例如, “D:D”或“AB:AB”然而它可能并不总是在这些列中,所以我需要搜索HEADER然后排序

任何帮助,将不胜感激!

excel vba sorting
1个回答
0
投票

看看这样的东西是否适合你......

该代码假定数据集之间没有空白列。

Sub SortColumns()
Dim i As Long, j As Long, lc As Long
Dim vKeys()
lc = ActiveSheet.UsedRange.Columns.Count
For i = lc To 1 Step -1
    If Columns(i).Hidden = False Then
        j = j + 1
        ReDim Preserve vKeys(1 To j)
        vKeys(j) = Cells(2, i).Address
    End If
Next i
'vKeys(4) --> First visible column from left
'vKeys(3) --> Second visible column from left
'vKeys(2) --> Third visible column from left
'vKeys(1) --> Fourth visible column from left
Range("A1").CurrentRegion.Sort key1:=Range(vKeys(4)), order1:=xlAscending, key2:=Range(vKeys(3)), order2:=xlAscending, key3:=Range(vKeys(2)), order3:=xlAscending, Header:=xlYes
Range("A1").CurrentRegion.Sort key1:=Range(vKeys(1)), order1:=xlAscending, Header:=xlYes
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.