我正在尝试创建一个循环变量,该变量通过字符串查找字符串数组,并在找到匹配项时将它们分配给组,但是,我并不需要它是完全匹配的,只是如果源字符串是LIKE搜索字符串。下面发布的示例代码:
Sub add_Categories()
Dim rRange As Range, rCell As Range
Dim wSheet As Worksheet
Dim wSheetStart As Worksheet
Dim strText As String
Set wSheetStart = ActiveSheet
wSheetStart.AutoFilterMode = False
Set rRange = Range("B1", Range("B65536").End(xlUp))
Application.DisplayAlerts = False
With wSheetStart
For Each rCell In rRange
If rCell Like "*Apple*" Then rCell.Offset(0, 2) = "Grocery"
If rCell Like "*Orange*" Then rCell.Offset(0, 2) = "Grocery
If rCell Like "*Mop*" Then rCell.Offset(0, 2) = "Kitchen"
If rCell Like "*Broom*" Then rCell.Offset(0, 2) = "Kitchen"
'If rCell Like "*Shirt*" Then rCell.Offset(0, 2) = "Clothing"
'If rCell Like "*Pants*" Then rCell.Offset(0, 2) = "Clothing"
Next rCell
End With
With wSheetStart
'.AutoFilterMode = False
.Activate
End With
On Error GoTo 0
Application.DisplayAlerts = True
End Sub
上面的示例每个类别只有两个字符串,但实际上我有数百个,并且将它们作为数组输入比将每个语句都有一行更容易。非常感谢任何帮助。
答案 0 :(得分:0)
这是一种可以使用数组并循环遍历它的方法:
Sub add_Categories()
Dim rRange As Range, rCell As Range, wSheet As Worksheet, wSheetStart As Worksheet, X As Long, FindArr As Variant, FoundArr As Variant
FindArr = Array("Apple", "Orange", "Mop", "Broom", "Shirt", "Pants")
FoundArr = Array("Grocery", "Grocery", "Kitchen", "Kitchen", "Clothing", "Clothing")
Set wSheetStart = ActiveSheet
wSheetStart.AutoFilterMode = False
Set rRange = Range("B1", Range("B" & Rows.Count).End(xlUp))
Application.DisplayAlerts = False
With wSheetStart
For Each rCell In rRange
For X = LBound(FindArr) To UBound(FindArr)
If rCell Like "*" & FindArr(X) & "*" Then rCell.Offset(0, 2) = FoundArr(X)
Next
Next
End With
With wSheetStart
'.AutoFilterMode = False
.Activate
End With
On Error GoTo 0
Application.DisplayAlerts = True
End Sub
将FindArr所需的内容和相应的输出添加到FoundArr
另请注意此处的更改:Set rRange = Range("B1", Range("B" & Rows.Count).End(xlUp))
使用rows.count而不是对行号进行硬编码。