我收到了几个不同的excel电子表格,其中包含多达30个不同的列标题。我真的只需要每个电子表格中的大约8或10列。我讨厌左右滚动找到所需的列。我想有一个宏,它弹出一个包含所有标题的对话框。我想选择所需的标题并将其从左到右剪切并粘贴,以便它们彼此相邻。
我是VBA的新手,正在尝试学习它,但这有点麻烦。帮助任何人吗?
我已经找到了每次都以相同的方式组织列的方法,但是每个电子表格都有不同的列和顺序,因此我需要能够选择它们。
答案 0 :(得分:0)
我建议将用户窗体与一个列表框一起使用,您可以在其中选择标题。 您可以尝试下面的代码。
要求: 用户表格 列表框>多选属性应为= 1 按钮>将所选数据加载到新工作表中
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