[英]VBA MACRO - Dynamically Select Columns in Excel Using ListBox
I have an excel file and what I did is that I add every column header to the listbox as items. 我有一个excel文件,我所做的是将每个列标题作为项目添加到列表框中。 Now, what I want to achieve is when I choose multiple items in listbox, it will copy the corresponding column and paste it to another workbook.
现在,我想要实现的是当我在列表框中选择多个项目时,它将复制相应的列并将其粘贴到另一个工作簿中。
I have this code right now, it can only copy and paste the first column that I chose from the listbox. 我现在有此代码,它只能复制并粘贴我从列表框中选择的第一列。 I hope someone could help me .
我希望有人能帮助我。
Private Sub CommandButton1_Click() ' generate result
Dim wkb As Workbook
Dim rng As Range
Dim cl As Object
Dim strMatch As String
Dim Size As Integer
Dim lRow As Long, lCol As Long
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Set rng1 = Cells.Find("*", [a1], xlFormulas, , xlByRows, xlPrevious)
Set rng2 = Cells.Find("*", [a1], xlFormulas, , xlByColumns, xlPrevious)
Set rng3 = Range([a1], Cells(rng1.Row, rng2.Column))
strMatch = ListBox2.List(0) 'Copying Respondent Number
Set rng = Range("A1:Z1")
For Each cl In rng
If cl.Value = strMatch Then
cl.EntireColumn.Copy 'Copy Selected Column
Set wkb = Workbooks.Add 'Adding New Workbook
ActiveSheet.Paste 'Paste Selected Column
Exit For
End If
Next cl
End Sub
proposed correction. 建议的更正。 This will create 1 workbook per selected column.
这将为每个选定的列创建1个工作簿。
Private Sub CommandButton1_Click() ' generate result
Dim rng As Range
Dim cl As Object
Dim strMatch As String
Dim , i As Integer
Dim lCol As Long
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
For i = 0 To ListBox1.ListCount - 1
strMatch = ListBox1.List(i) 'Copying Respondent Number
Set rng = Range(Cells(1, 1), Cells(1, lCol))
Set cl = rng.Find(strMatch, lookat:=xlWhole)
If Not cl Is Nothing Then
cl.EntireColumn.Copy 'Copy Selected Column
Set wkb = Workbooks.Add 'Adding New Workbook
ActiveSheet.Paste 'Paste Selected Column
End If
Next i
End Sub
you could try this 你可以试试这个
Option Explicit
Private Sub CommandButton1_Click()
Dim i As Long
Dim colsIndexStrng As String
Dim copyRng As Range
With Me.ListBox2
For i = 0 To .ListCount - 1
If .selected(i) Then colsIndexStrng = colsIndexStrng & Cells(1, i + 1).Address(False, False) & ","
Next i
End With
If colsIndexStrng = "" Then Exit Sub
Set copyRng = Range(Left(colsIndexStrng, Len(colsIndexStrng) - 1)).EntireColumn
With Workbooks.Add
copyRng.Copy ActiveSheet.Range("A1")
End With
ActiveWorkbook.Close True
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.