使用 InStr/InStrB 查找 Chr(13)

Using InStr/InStrB to find Chr(13)

最近我遇到了这样一行:

Private Function FindCR(BinaryString)
  FindCR = InstrB(1, BinaryString, Chr(13))
End Function

基本上,我给它一个二进制字符串,它应该给我回车索引 returns。对于这个例子,让我们使用 ChrB(65) & ChrB(13) & ChrB(66) & ChrB(13) & ChrB(67) & ChrB(0),它等同于:

A

B

C

但是,在这种情况下 FindCR 会 return 我 0 因为 Chr(13) = [=15=] 并且我的字符串看起来像 [=16=].

我试图通过将 Chr(13) 替换为 ChrB(13) 来绕过它(CR 的二进制表示,而不是 Char 表示,所以 </code> 而不是 <code>[=15= ]), 但 instrB returns Arg1 (在本例中为 1) 当 Arg3 的长度为 0 (而 lenB(ChrB(13)) 为 1, len(ChrB(13)) 为 0.

是否有任何方法可以在二进制字符串中找到第一个回车符 return 而无需操作字符串 and/or 以 \xx 形式处理字符?

在处理二进制字符串时,您可能会通过仅检查回车符来限制自己 returns。根据我的经验,有人可以对略有不同的字符串使用不同的文本编辑器 and/or 您的源数据可能会发生变化(甚至从测试到生产)。行尾序列可以是 vbCR 或 vbCR+vbLF 或什至其他组合。我建议自己滚动以获得您可能需要的灵活性:

Option Explicit

Private Function FindByteCode(binString() As Byte, _
                              Optional findChar As String = vbCr, _
                              Optional startChar As Long = 0) As Long
    Dim i As Long
    Dim start As Long
    Dim eos As Long
    If startChar > 0 Then
        start = startChar
    Else
        start = LBound(binString)
    End If
    eos = 0
    For i = start To UBound(binString)
        If binString(i) = AscB(findChar) Then
            eos = i
            Exit For
        End If
    Next i
    FindByteCode = eos
End Function

Sub test()
    Dim testStr As String
    testStr = "where is the end of the first vbCR " & Chr(13) & _
              " and then the second?" & vbCr & vbLf
    Debug.Print "first  vbCR at " & FindByteCode(StrConv(testStr, vbFromUnicode))
    Debug.Print "second vbCR at " & FindByteCode(StrConv(testStr, vbFromUnicode), startChar:=36)
    Debug.Print "first  vbLF at " & FindByteCode(StrConv(testStr, vbFromUnicode), findChar:=vbLf)
End Sub