VBA 比较字符串(检查字符串一是否包含字符串二)

VBA compare string ( check if string one contains string 2)

我在比较两个字符串时遇到问题。该方法似乎无法以某种方式起作用。我尝试了以下功能:

  1. 方法:

    If StrComp(logic_string, RSTA_ISIN_clean) Then
        rng.Offset(0, 16) = "OK(ISIN in RSTA)"
        rng.Offset(0, 16).Interior.Color = 5296274
    Else
        rng.Offset(0, 16) = "NG(ISIN not RSTA or check RSTA)"
        rng.Offset(0, 16).Interior.Color = 255
    End If
    
  2. 方法:

     If InStr(1, RSTA_ISIN_clean, logic_string, vbTextCompare) Then
         rng.Offset(0, 16) = "OK(ISIN in RSTA)"
         rng.Offset(0, 16).Interior.Color = 5296274
     Else
         rng.Offset(0, 16) = "NG(ISIN not RSTA or check RSTA)"
         rng.Offset(0, 16).Interior.Color = 255
     End If
    

在 logic_string 中我有值 "FR0012915700",在 RSTA_ISIN 中我有值 = " Old ISIN: FR0012915700"

我想做的就是检查 RSTA_ISIN 是否在 logic_string 中,如果是,我想在单元格中写入 OK。 (试图在此处获取包含方法)

可能是 logic_string 出了问题,因为它有时会给我空格 -> 所以 logic_string 在调试模式下看起来像这样“FR0004052561” -> 我尝试 trim 带有 Trim 的空格,但这也不起作用。

我也尝试了 InStr 功能,但它也不起作用

有人可以帮忙吗

这是我在调试模式下得到的:

请检查您的变量。 "RSTA_ISIN_clean" 或 "RSTA_ISIN" 作为变量

Sub test1()

Dim RSTA_ISIN_clean As String
Dim logic_string As String
Dim Rng As Range


Set Rng = ActiveSheet.Cells(1, 30)

logic_string = "FR0012915700"

RSTA_ISIN_clean = "Old ISIN: FR0012915700"

logic_string = Trim(logic_string)
RSTA_ISIN_clean = Trim(RSTA_ISIN_clean)


If StrComp(logic_string, RSTA_ISIN_clean) Then
    Rng.Offset(0, 16) = "OK(ISIN in RSTA)"
    Rng.Offset(0, 16).Interior.Color = 5296274
Else
    Rng.Offset(0, 16) = "NG(ISIN not RSTA or check RSTA)"
    Rng.Offset(0, 16).Interior.Color = 255
End If



End Sub

我觉得你并不真的想使用 StrCmp function at all; it sounds as if your find-string-within-another-string should be handled by the InStr function。请单击这些链接并阅读 MSDN 文档以做出决定。

Dim logic_string as String, RSTA_ISIN_clean as String

logic_string = "FR0012915700"
RSTA_ISIN_clean = " Old ISIN: FR0012915700"

If CBool(InStr(1, RSTA_ISIN_clean, logic_string, vbTextCompare)) Then
    rng.Offset(0, 16) = "OK(ISIN in RSTA)"
    rng.Offset(0, 16).Interior.Color = 5296274
Else
    rng.Offset(0, 16) = "NG(ISIN not RSTA or check RSTA)"
    rng.Offset(0, 16).Interior.Color = 255
End If

尝试使用 Like 运算符:

Dim logic_string As String, RSTA_ISIN_clean As String

  logic_string = " FR0012915700"
  RSTA_ISIN_clean = " Old ISIN: FR0012915700"


 If RSTA_ISIN_clean Like "*" & Trim(logic_string) & "*" Then
    Rng.Offset(0, 16) = "OK(ISIN in RSTA)"
    Rng.Offset(0, 16).Interior.Color = 5296274
 Else
    Rng.Offset(0, 16) = "NG(ISIN not RSTA or check RSTA)"
    Rng.Offset(0, 16).Interior.Color = 255
 End If`