Dialog wdDialogFileOpen并不总是立即更新ActiveDocument

问题描述 投票:0回答:1

我将其发布是为了给遇到相同问题的任何其他人带来好处,但会感谢其他人可能提出的任何其他评论。

以下代码已经运行了多年没有问题:

If Dialogs(wdDialogFileOpen).show <> -1 Then
    GoTo ImportTablesEnd
Else
    Set sourceDoc = ActiveDocument
    ....
End If

意图是,在DocumentA中运行此代码,例如,提示用户打开文件(称为DocumentB),该文件稍后将在代码中使用。 DocumentB通过变量sourceDoc访问。

我最近在测试产品的新版本时经常使用此代码,并且我发现该代码现在间歇性地失败,只要sourceDoc最终指向DocumentA而不是DocumentB

[似乎ActiveDocument并非总是从wdDialogFileOpen返回时立即被设置。这可能是由于最近进行的Office 365维护-我不知道。

vba word-vba
1个回答
0
投票

我已经绕过了这个问题:

   Set fileDialog = Dialogs(wdDialogFileOpen)
   If fileDialog.show <> -1 Then
       GoTo ImportTablesEnd
   Else
       Set sourceDoc = Documents(replace(fileDialog.Name, Chr(34), "")) 
       ...     

用空字符串替换chr(34)的原因是fileDialog.Name如果所选文件名包含空格,则将其用引号引起来。如果不选择替换,则如果用户选择名称包含空格的文件,则仅使用Documents(fileDialog.Name)即可得到Run-time error 4160 "Bad file name"

© www.soinside.com 2019 - 2024. All rights reserved.