我在分离列表框项目时遇到问题,因此我可以循环运行它们。我知道这个自动取款机会收取所有物品并尝试将它们运行,但我不知道如何将它们分开。 代码如下:
Dim SelectedItems As String
Dim LastRow As Long
LastRow = ActiveSheet.Range("F1").SpecialCells(xlCellTypeLastCell).Row
For i = 0 To ListBox2.ListCount - 1
If ListBox2.Selected(i) = True Then
SelectedItems = SelectedItems & ListBox2.List(i) & vbNewLine
End If
Next i
If SelectedItems = "" Then
MsgBox "Please select minimum one country"
Else
For Each SelectedItems In ListBox2
For i = 11 To LastRow
If Range("F" & i).Value = SelectedItems Then
Rows(i).EntireRow.Hidden = True
Else: Rows(i).EntireRow.Hidden = False
End If
Next i
Next SelectedItems
有人可以帮忙吗?
Dim SelectedItems As String, LastRow As Long
Dim selItem As Variant, selItems As Variant
LastRow = ActiveSheet.Range("F1").SpecialCells(xlCellTypeLastCell).Row
For i = 0 To ListBox2.ListCount - 1
If ListBox2.Selected(i) = True Then
SelectedItems = SelectedItems & ListBox2.List(i) & vbNewLine
End If
Next i
Stop
If SelectedItems = "" Then
MsgBox "Please select minimum one country"
Else
SelectedItems = left(SelectedItems, Len(SelectedItems) - 1)
selItems = Split(SelectedItems, vbNewLine)
For Each selItem In selItems
For i = LastRow To 11 Step -1
If CStr(Range("F" & i).value) = CStr(selItem) Then
Stop
Rows(i).EntireRow.Hidden = True
'Else: Rows(i).EntireRow.Hidden = False
End If
Next i
Next
End If
如果不将字符串拆分为元素,您的代码将无法识别字符串中的每个选定项目。 编辑:转换测试代码中的代码。我将(在评论中)向您解释如何检查。
注意:我只是想让你的代码可行。否则,您可以使用 Excel AutoFilter 直接进行过滤(当然是在 VBA 中)...
所以只是一个关于我如何解决这个问题的小例子,避免多个循环:
样本数据:
用户表单示例:
用户表单示例代码:
Option Explicit
Private Sub CommandButton1_Click()
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim x As Long, lr As Long
Dim rng As Range
'Check if anything has been selected at all
If Me.ListBox1.ListIndex = 0 Then Exit Sub
'Capture selected items in your ListBox
For x = 0 To Me.ListBox1.ListCount - 1
If Me.ListBox1.Selected(x) Then
dict(ListBox1.List(x)) = 1
End If
Next x
'Filter the range accordingly
With Sheet1
lr = .Cells(.Rows.Count, 1).End(xlUp).Row
Set rng = .Range("A1:A" & lr)
rng.AutoFilter 1, Array(dict.keys), xlFilterValues
End With
End Sub
Private Sub UserForm_Initialize()
Dim lr As Long
'Populate your ListBox
With Sheet1
lr = .Cells(.Rows.Count, 1).End(xlUp).Row
Me.ListBox1.RowSource = .Range("A2:A" & lr).Address
End With
End Sub
结果示例: