使用If宏查找具有特定文本的单元格

Jam*_*ker 3 excel vba excel-vba

我有一张包含很多宏的成本单.其中一个宏是在工作表底部添加新的订单项.我想输入一个If代码,说如果我添加的项目以文本"Custom"开头,后面我希望它找到该单元格并选择它.下面是我正在尝试的代码但它调试类型不匹配并突出显示Custom = Range("B:B").值行.任何帮助深表感谢.

 Dim Custom As String
    Custom = Range("B:B").Value
    If Custom Like "Custom *" Then
    Cells.Find(What:="Custom ", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=True, SearchFormat:=False).Activate
    ActiveCell.FormulaR1C1 = ("Test")
    End If
Run Code Online (Sandbox Code Playgroud)

Sid*_*out 9

你不需要使用LIKE它.直接使用.Find请参阅此示例

注意使用LookAt:=xlPart.这将确保如果"Custom "单元格中有任何内容,代码将捕获它.

Sub Sample()
    Dim ws As Worksheet
    Dim aCell As Range

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        Set aCell = .Columns(2).Find(What:="Custom ", LookIn:=xlValues, _
                    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                    MatchCase:=False, SearchFormat:=False)
        If Not aCell Is Nothing Then
            aCell.Value = "Test"
        Else
            MsgBox "Not Found"
        End If
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)