VBA 检测和比较字符串

问题描述

在运行此代码后,我设法得到了答案。 但我仍然收到运行时错误 13 消息。你能帮我解决吗? @PEH

 Dim ws As Worksheet
 Dim str As String

 str = "Attention for shipment on track"

 Set ws = Worksheets("Report")

 Dim lastrows As Long
 lastrows = ws.cells(Rows.Count,1).End(xlUp).Row

 Dim i As Long
 For i = 2 To lastrows
    If InStr(1,ws.cells(i,43).Value,str) > 0 Then
        ws.cells(i,63).Value = "OK"
    End If
  Next i 

解决方法

请注意,InStr 返回的是一个位置,而不是 True 语句所需的 FalseIf。如果您的意思是变量 "str",则 "str" 也正在寻找这 3 个字符 str,您需要在此处删除引号。

最后InStr function的第一个参数是起始位置。
正如@FunThomas 在评论中指出的,InStr function 开头的 Start 参数是可选的,确实可以省略。

Option Explicit

Sub track()        
    Dim str As String
    str = "Attention for shipment on track"

    Dim ws As Worksheet
    Set ws = Worksheets("Report")

    Dim lastrows As Long
    lastrows = ws.cells(Rows.Count,1).End(xlUp).Row
    
    Dim i As Long
    For i = 2 To lastrows         
        If InStr(1,ws.cells(i,43).Value,str) > 0 Then
            ws.cells(i,63).Value = "OK"  
        End If
    Next i
End Sub

确保始终使用 Option Explicit 并正确声明所有变量。