在 vba Office 宏中使用全局对象

Use of Global objects in vba Office macros

请解释以下内容:

  1. Word.Application和Word.Global有什么区别?

  2. 在 VBA Word 宏中,对 Application 和 Selection 等全局对象的引用是否始终绑定到 Word,或者如果 Excel是运行在前台吗?

  3. 如果我想打开 Word,启动一个(又长又复杂的)宏 运行,然后将焦点切换到另一个应用程序,例如Excel,我是否需要修改对 ActiveDocument、Application 和 Selection 等全局变量的引用以明确指向对象的 Word 版本,以便它们不会与相同的 Excel 版本混淆?

我不确定你所说的 Word.Global 是什么意思,你能解释一下吗?最好有一些使用这种调用的代码示例。

In a VBA Word macro, are references to Global objects like Application and Selection always bound to Word or could they inadvertently refer to Excel objects if Excel is running in the foreground?

除非另有限定,Application 总是指当前应用程序对象。如果您的 VBA 在 Word 中,那么这将始终 return Word.Application 对象。

If I want to open Word, start a (long, complicated) macro running and then switch focus to another application e.g. Excel,

Word 中的宏不会被其他前台任务混淆,但 Word 应用程序在宏的 运行 时间内可能没有响应。

您可能需要采取措施防止 Word 应用程序在 运行 时间内获得焦点。对于包括您在内的大多数应用程序,我认为这不会出现问题。当您将文档拆分为多个 "new" 文档时,创建新的 Document 对象并分配 visible=False:

Set doc = Documents.Add(Visible:=False)