VBA字符串与回车的比较

时间:2017-11-07 11:47:58

标签: excel string vba comparison carriage-return

我正在尝试比较2个字符串以找到匹配项。 代码打开许多文件,并为每个文件提取2个字符串 据说与我定义的那些相匹配。 但是,单元格中的一个字符串包含回车符,这是 我之所以无法得到匹配的原因。 真的很感谢您的帮助! 提前谢谢。

我的代码的相关部分用于比较如下:

Dim i As Integer
Dim a, WScount, rows, j As Integer
Dim temp As String
Dim check1, check2 As Boolean
Dim str1, str2 As String

i = 1
j = 1

str1 = "Manufacturers Number"
str2 = "Manufacturers" & vbCrLf & " Number"

For Each WS In Worksheets
    N = 0
    rows = 1
    While N < 7
        temp = src.ActiveSheet.Cells(rows, 2)
        check1 = StrComp(str1, temp, vbTextCompare)
        check2 = StrComp(str2, temp, vbTextCompare)
        If check1 = 0 Or check2 = 0 Then
            For k = rows + 1 To 100
                temp = Cells(k, 2)
                If Not StrComp("", temp, vbTextCompare) = False Then
                    ThisWorkbook.Worksheets(1).Cells(j, 3) = temp
                    j = j + 1
                End If
            Next k
        End If
            rows = rows + 1
            N = N + 1
    Wend

Next WS

1 个答案:

答案 0 :(得分:1)

a等于a 10和13。 “新线”和“回车”。 Ascii Table

因此,您可以简单地使用这两个值并尝试一下:

vbCrLf

asc函数检查Option Explicit Public Sub TestMe() Dim str1 As String Dim str2 As String str1 = "Manufacturers Number" str2 = "Manufacturers" & vbCrLf & " Number" str1 = stripTheString(str1) str2 = stripTheString(str2) Debug.Print str1 = str2 End Sub Public Function stripTheString(strToStrip As String) As String Dim cnt As Long Dim ascVal As Long Dim newStr As String For cnt = 1 To Len(strToStrip) ascVal = Asc(Mid(strToStrip, cnt, 1)) If Not (ascVal = 10 Or ascVal = 13) Then newStr = newStr & Mid(strToStrip, cnt, 1) End If Next cnt stripTheString = newStr End Function stripTheString并将其从代码中删除。上面的代码可能有点问题,如果你的新行没有回车符,只要它会删除new line函数中的新行。