我收到了几个不同的 Excel 电子表格,其中包含多达 30 个不同的列标题。我真的只需要每个电子表格中大约 8 或 10 列。我厌倦了左右滚动找到我需要的列。我想要一个宏,它会弹出一个对话框,其中包含所有可用的标题。我想选择我想要的标题,然后从左到右剪切和粘贴它们,使它们彼此相邻。
我是 VBA 的新手并试图学习它,但这有点超出我的理解。帮助任何人?
我已经找到了每次都以相同的方式组织我的列的方法,但每个电子表格都有不同的列和顺序,因此我需要能够选择它们。
我建议使用带有列表框的用户表单,您可以在其中选择标题。你可以试试下面的代码。
要求:Userform ListBox > Multiselect Property 应该是 = 1 Button > 将选中的数据加载到新的工作表
Dim mySH As Worksheet
Dim oSH As Worksheet 'Output Worksheet
Private Sub cmd_load_Click()
Dim i As Integer
Dim col_count As Integer
col_count = 1
Dim col_header As String
Dim ns_srow As Integer
ns_srow = 1
'LOOP THRU ALL ITEMS IN LISTBOX AND GET ALL SELECTED
For i = 0 To lst_header.ListCount - 1
If lst_header.Selected(i) Then
col_header = lst_header.List(i)
'FIND THE COLUMN HEADER POSITION AND TRANSFER TO NEWSHEET THE DATA
For a = 1 To mySH.Cells(1, Columns.Count).End(xlToLeft).Column
If mySH.Cells(1, a).Value = col_header Then
For b = 1 To mySH.Cells(Rows.Count, a).End(xlUp).Row
oSH.Cells(ns_srow, col_count).Value = mySH.Cells(b, a).Value
ns_srow = ns_srow + 1
Next b
col_count = col_count + 1
ns_srow = 1
Exit For
End If
Next a
End If
Next i
MsgBox "Data Completed"
End
End Sub
Private Sub UserForm_Initialize()
Set mySH = ThisWorkbook.Sheets("Data") 'name of your raw data worksheet
Set oSH = ThisWorkbook.Sheets("Output") 'output worksheet
'Assuming that column header is at row 1
For a = 1 To mySH.Cells(1, Columns.Count).End(xlToLeft).Column
lst_header.AddItem mySH.Cells(1, a).Value
Next a
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句