简体   繁体   English

在VBA中查找列并进行排序

[英]Find column in VBA and sort

Hi there I'm trying to create a macro to make it easier to sort data exported from a robot 嗨,我正在尝试创建一个宏,以便更轻松地对从机器人导出的数据进行排序

The trouble is the columns can change places due to the way in which the robot does the testing 问题在于,由于机器人进行测试的方式,色谱柱会改变位置

Many of the columns are useless and so I have made a macro to hide the unused columns and now I would like to add a macro that sorts these remaining 4 columns in Ascending order but I just can't crack it 许多列是无用的,因此我做了一个宏来隐藏未使用的列,现在我想添加一个宏,以按升序对剩余的4列进行排序,但是我无法破解它

So far I have 到目前为止,我有

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

Which hides every column other then the named ones but I can't get it to sort the data after this 这会隐藏除已命名列之外的所有其他列,但此后我无法对其进行排序

I've tried to findcolumn/selectcolumn and sort but for some reason the macro seems to run and not actually sort 我尝试过查找列/选择列并进行排序,但是由于某种原因,宏似乎在运行并且实际上未进行排序

Also tried recording macro but as the columns move the code keeps defining the columns to sort as eg "D:D" or "AB:AB" however it might not always be in these columns so I need to SEARCH FOR THE HEADER then sort 也尝试记录宏,但是随着列的移动,代码会不断定义要排序的列,例如“ D:D”或“ AB:AB”,但是它可能并不总是出现在这些列中,因此我需要搜索HEADER然后进行排序

Any help would be appreciated! 任何帮助,将不胜感激!

See if something like this works for you... 看看类似的东西对您有用...

The code assumes that there is no blank column in between the data set. 该代码假定数据集之间没有空白列。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM