简体   繁体   中英

Excel VBA: string comparison does not work

I am trying to compare an activeSheet code name with simple string, but the result is always true. I debbuged that and the variables values are different.

Sub Button_Supprimer()
    
Dim a, b As String
a = CStr(ActiveSheet.CodeName)
b = "Sheet1"

If (a = b) Then:
    frmSupprimer.Caption = "Supprimer un matériel"
    'frmSupprimer.UserForm_Initialize ("Matériel")
    frmSupprimer.Show
End               
End Sub

result

The result isn't always true, it's just that no statement in your code is actually conditional.

The existence of the : instructions separator token should generally be forgotten and left for golfed-up minimized fire-and-forget code that you would run from the immediate pane (Ctrl+G).

By terminating If {condition} Then with a colon, you have made the conditional expression be just an empty instruction.

Without it, the code stops compiling and you get a "If block without End If" compile error.

The correct syntax for a conditional block of code is as follows:

If {condition} Then
    {conditional statements}
End If

Note that the End instruction is essentially a nuclear option for terminating the execution of the program; globals get reset to their default values, the execution context is terminated: rule of thumb, you want to let execution reach the End Sub statement and let the VBA runtime unwind its call stack normally: the End instruction stops everything dead in its tracks right there & then - and it's very, very rare that you actually need to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM