I am trying to compare 2 strings to find a match. The code opens many files and for each file it fetches 2 strings that supposedly match to the ones I defined. However, one of the strings in a cell contains a carriage return and this is the reason why I can't seem to get a match. Your help will be truly appreciated! Thanks in advance.
The related parts of my code for the comparison are the following:
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
The vbCrLf
is equal to asc
10 and 13. E.g. "new line" and "carriage return" . Ascii Table.
Thus, you could simply these two values and give it a try:
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
The stripTheString
function checks for new line
or carriage return
and removes them from the code. The code above could be a bit problematic, if you have new line without carriage return after it, as far as it will erase the new line in the stripTheString
function.