通过 VBA 添加新列时,我的文件遇到问题。单击按钮时,它会获取进程 ID 号并在不同工作表的表上创建一列。
每次添加新列时,如何按字母顺序(按标题值)重新排列列顺序。
列数是动态的,在用户创建进程之前我无法知道标题名称。
这是我当前的代码:
'Create a new column on the process assignment table
Sheets("T_PRAS").ListObjects("T_PRAS").ListColumns.Add.Name = "PR_" & Sheets("Administrador").Range("B53").Value
最佳答案
这经过了轻微的测试,但我在对工作表进行排序时做了类似的事情,这似乎也适用于您的表格。
Dim x As Long, y As Long, tbl As ListObject
Set tbl = ActiveSheet.ListObjects("T_PRAS")
' Loop through each column
With tbl.ListColumns
For x = 1 To tbl.ListColumns.Count
For y = x + 1 To tbl.ListColumns.Count
If .Item(y).Name < .Item(x).Name Then
.Item(y).Range.Cut
.Item(x).Range.Insert xlRight
End If
Next y
Next x
End With
本质上,你有两个循环。第一个循环将列名称与第二个循环进行比较,如果第二个循环的名称位于第一个循环之前,则它将移动该列。
关于excel - 添加新列时,VBA-Excel 按字母顺序重新排列列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53381921/