简体   繁体   English

Excel VBA:字符串比较不起作用

[英]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.我正在尝试将 activeSheet 代码名称与简单字符串进行比较,但结果总是正确的。 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). :指令分隔符标记的存在通常应该被忘记,并留给您将从即时窗格 (Ctrl+G) 运行的最小化的即发即弃代码。

By terminating If {condition} Then with a colon, you have made the conditional expression be just an empty instruction.通过使用冒号终止If {condition} Then ,您使条件表达式只是一个空指令。

Without it, the code stops compiling and you get a "If block without End If" compile error.没有它,代码将停止编译,并且您会收到“没有 End If 的 If 块”编译错误。

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;请注意, End指令本质上是一个用于终止程序执行的核选项; 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.全局变量被重置为其默认值,执行上下文终止:根据经验,您想让执行到达End Sub语句并让 VBA 运行时正常展开其调用堆栈: End指令将所有内容都停止在其轨道上& 然后 - 你真的需要这样做是非常非常罕见的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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