【发布时间】:2018-09-16 06:28:12
【问题描述】:
我是编码初学者。所以我想知道如何使用嵌套来编写一个宏(用于 VBA Word),该宏在指定文件夹中的所有文档中运行多个其他宏。我试图通过让外部循环打开文件夹中的所有文档来使用嵌套(用户将使用 InputBox 输入文件夹的位置),并且在此循环中,将应用所有宏。
到目前为止,我知道这是完美的(代码打开了指定文件夹中的所有文档);
Sub nestingMacro()
Dim currentFile As String
Dim location As String
location = InputBox("Location of folder")
If Right(location, 1) <> "\" Then location = location + "\"
currentFile = Dir(location & "*.doc*")
Do While (currentFile <> "")
Documents.Open FileName:=location & currentFile
currentFile = Dir()
Loop
End Sub
我尝试添加以下内容;
Sub nestingMacro()
Dim currentFile As String
Dim location As String
location = InputBox("Location of folder")
If Right(location, 1) <> "\" Then location = location + "\"
currentFile = Dir(location & "*.doc*")
Do While (currentFile <> "")
Documents.Open FileName:=location & currentFile
currentFile = Dir()
If currentFile <> "" Then
'the name of the macros below
Call findReplaceStyle
Call countErrorsQuality
Call saveClose
End If
Loop
End Sub
是的,它会打开一个文件夹中的所有文档,但是,它只在其中两个文档上运行宏,而其他文档则没有任何反应。我该如何解决这个问题?
是否有更好的方法来编写函数 IF,以便使用嵌套在所有文档上运行宏?
还有没有办法运行宏而不实际调用它们的名字?
谢谢!
【问题讨论】:
-
我们不明白您所说的“嵌套”是什么意思。请解释。 FWIW 我怀疑您可能遇到了竞争情况 - 打开文件的代码可能正在执行,而无需等待宏在每个文档上运行/完成。我也不知道你最后一个问题的确切含义,但你可以(并且可能应该)省略关键字
Call- VBA 不需要它。但是您确实需要使用宏的名称。 -
我所说的嵌套是指当一个结构包含在另一个结构中时——(对于 VBA)是指代码在彼此内部具有 IF 分支和 Do-While 循环。所以......在Do-While中,您可能有一个IF分支,或者在IF中您可能有一个Do-While,或者Do-while中的Do-While,或者IF中的IF。谢谢!
-
测试一下:在 Loop 行放一个断点,这样代码每次碰到这一行就停止。每次只需按 F5 即可。那么事情是否如你所愿?如果是,那么在宏“全速”运行时,在打开下一个文档之前,各种调用都没有完成。要缩小范围,您需要注释掉代码,直到找到为止。
标签: vba function if-statement ms-word