IF-THEN w/ strings in VBA

2019-09-08 18:58发布

I am trying to check if two cells values are equal to each other by reading in the value with strings. Using a for loop to step through to find the match of the IF-THEN statement.

When stepping through the program It shows that the values are equal at one point but the IF-THEN comparison just keeps running I can not figure out why it will not stop when they are equal.

Dim ws As Worksheet
Dim lcol As Long
Dim Val As String
Dim Check As String

'Read in value for audit to continue

Val = ContTextBox.Value

'Make Master Sheet Active
 Worksheets("Master").Activate

Set ws = ThisWorkbook.Sheets("Master")


'Finds next empty column

  With ws
        lcol = .Cells(11, .Columns.Count).End(xlToLeft).Column + 1
  End With


'i needs to be set to minimum limit
'Begin loop of search

For j = 1 To lcol
    Check = Cells(11, j).Value

   If Check = Val Then

       Unload Me
       Assetlookup.Show

    End If

  Next j

Unload Me

1条回答
叼着烟拽天下
2楼-- · 2019-09-08 19:30

How 'identical' are the two strings? Is one capitalized and the other not? Does one have leading/trailing zeros? Does one have non-printable characters?

Try this, which cleans each term before comparing them:

If AllCleanedUp(Check) = AllCleanedUp(Val) Then

...

Which refers to the following function:

Function AllCleanedUp (DirtyString byVal) As String

    AllCleanedUp = Trim(Application.Clean(Lcase(DirtyString)))

End Function
查看更多
登录 后发表回答