Excel VBA-使用“分类”;例如;

Excel VBA-使用“分类”;例如;,excel,vba,Excel,Vba,我正在创建一个宏来完成这里概述的几乎完全相同的操作: 我的问题是,在上面示例中的代码中,如“”用于检查描述是否与关键字匹配,如果匹配,则提取相应的类别名称。在我的例子中,我目前没有每个可能的类别的关键字(但随着我收集更多的事务数据,最终会有关键字),这意味着我的关键字列中的一些单元格是空的,并且上面代码的编写方式在遇到空单元格时认为patternfound=true。如何使用“Like”或类似的内容修改If语句,使其在完全为空的单元格上跳过,并且仅在单元格中有一些字符(匹配)时才提供匹配 我找

我正在创建一个宏来完成这里概述的几乎完全相同的操作:

我的问题是,在上面示例中的代码中,如“”用于检查描述是否与关键字匹配,如果匹配,则提取相应的类别名称。在我的例子中,我目前没有每个可能的类别的关键字(但随着我收集更多的事务数据,最终会有关键字),这意味着我的关键字列中的一些单元格是空的,并且上面代码的编写方式在遇到空单元格时认为patternfound=true。如何使用“Like”或类似的内容修改If语句,使其在完全为空的单元格上跳过,并且仅在单元格中有一些字符(匹配)时才提供匹配

我找到了一个解决办法,在空单元格中加上“N/a”,但我不想这样做。这是我的密码:

Sub Categorize()

Dim lastrow As Long, lastrow2 As Long
Dim i As Integer, j As Integer
Dim PatternFound As Boolean

Call speedup

lastrow = Sheets("Categorization").Range("B" & Rows.Count).End(xlUp).Row
lastrow2 = Sheets("Cleaned Spend Data").Range("C" & Rows.Count).End(xlUp).Row


For i = 4 To lastrow2

    PatternFound = False

    j = 1

    Do While PatternFound = False And j < lastrow

        j = j + 1

        If UCase(Sheets("Cleaned Spend Data").Range("B" & i).Value) Like "*" & UCase(Sheets("Categorization").Range("B" & j).Value) & "*" Then
            Sheets("Cleaned Spend Data").Range("D" & i).Value = Sheets("Categorization").Range("A" & j).Value
            PatternFound = True
        End If

      Loop

    Next i

    Call normal

End Sub
子分类()
将最后一行的长度调暗,最后一行的长度调暗
尺寸i为整数,j为整数
找到的模糊模式为布尔型
呼叫加速
lastrow=工作表(“分类”).Range(“B”和Rows.Count)。End(xlUp)。Row
lastrow2=工作表(“已清理的支出数据”)。范围(“C”和行数。计数)。结束(xlUp)。行
对于i=4到最后一行2
PatternFound=False
j=1
当PatternFound=False且j

谢谢

您可以测试空单元格

此外,使用工作表中的两个变量,您的代码可能会更干净

Sub Categorize()

    Dim lastrow As Long, lastrow2 As Long
    Dim i As Integer, j As Integer
    Dim PatternFound As Boolean, shtCat As Worksheet, shtCleaned As Worksheet
    Dim v, t

    Set shtCat = Sheets("Categorization")
    Set shtCleaned = Sheets("Cleaned Spend Data")

    Call speedup

    lastrow = shtCat.Range("B" & Rows.Count).End(xlUp).Row
    lastrow2 = shtCleaned.Range("C" & Rows.Count).End(xlUp).Row

    For i = 4 To lastrow2
        v = UCase(UCase(shtCleaned.Range("B" & i).Value))
        For j = 1 To lastrow
            t = UCase(Sheets("Categorization").Range("B" & j).Value)
            If Len(t) > 0 And v Like "*" & t & "*" Then
                shtCleaned.Range("D" & i).Value = shtCat.Range("A" & j).Value
                Exit For
            End If
        Next j
    Next i

    Call normal

End Sub

此外,我还通过在所有空白单元格中添加“N/A”来解决这个问题,但我不想使用这个解决方法。这是我的代码:非常好!非常感谢你的帮助。