且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该在 VB/VBA 中使用 Call 关键字吗?

更新时间:2023-02-06 18:10:46

啊哈.我一直对此感到疑惑,甚至阅读一本两英寸厚的关于 VBA 的书基本上都说不要使用它,除非您想使用 VBE 的查找功能来轻松查找大型项目中的调用.

Ah ha. I have long wondered about this and even reading a two inch thick book on VBA basically says don't use it unless you want to use the Find feature of the VBE to easily find calls in large projects.

但我刚刚发现了另一个用途.

But I just found another use.

我们知道可以用冒号字符连接代码行,例如:

We know that it's possible to concatenate lines of code with the colon character, for example:

Function Test(mode as Boolean) 
    if mode = True then x = x + 1 : Exit Sub
    y = y - 1
End Sub

但是,如果您在行首使用过程调用执行此操作,则 VBE 假定您指的是标签并删除任何缩进,将行与左边距对齐(即使该过程按预期调用):

But if you do this with procedure calls at the beginning of a line, the VBE assumes that you're referring to a label and removes any indents, aligning the line to the left margin (even though the procedure is called as intended):

Function Test()
Function1 : Function2
End Function

使用 Call 语句允许在保持代码缩进的同时串联过程调用:

Using the Call statement allows concatenation of procedure calls while maintaining your code indents:

Function Test()
    Call Function1 : Call Function2
End Function

如果你在上面的例子中不使用Call语句,VBE会假设Function1"是一个标签,并在代码窗口中左对齐,即使它不会导致错误.

If you don't use the Call statement in the above example, the VBE will assume that "Function1" is an label and left align it in the code window, even though it won't cause an error.