vba 在多个活动工作簿之间工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41730885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 11:54:56  来源:igfitidea点击:

Working between multiple active workbooks

excelvbaexcel-vba

提问by Scott

Macro 1 code is stored in Workbook 1. Command button 1 triggers opening a user selected workbook. Let's call that Workbook 2 (although the actual Workbook name is different each time). Macro 1 runs codes (mostly formatting commands) in Workbook 2.

宏 1 代码存储在工作簿 1 中。命令按钮 1 触发打开用户选择的工作簿。我们称其为 Workbook 2(尽管实际的 Workbook 名称每次都不同)。宏 1 运行工作簿 2 中的代码(主要是格式化命令)。

Macro 1 ends. Workbook 2 remains open. After some manual intervention by user on Workbook 2, user clicks Command button 2 in Workbook 1, which triggers Macro 2.

宏 1 结束。工作簿 2 保持打开状态。在用户对工作簿 2 进行一些手动干预后,用户单击工作簿 1 中的命令按钮 2,这会触发宏 2。

Macro 2 starts by activating Workbook 2 again, running code. At one point, code says to Open another user selected Workbook. Let's call it Workbook 3 (again, filename can be different). Then Macro 2 has codes that takes actions back in Workbook 2. Then goes back to Workbook 3.

宏 2 通过再次激活工作簿 2 开始运行代码。有一次,代码说要打开另一个用户选择的工作簿。我们称之为工作簿 3(同样,文件名可以不同)。然后宏 2 具有在工作簿 2 中执行操作的代码。然后返回到工作簿 3。

The problem I am having is I cannot figure out how to Dim each of these workbooks given the Workbook names/WorkSheet names change. Also, with new Workbooks being opened at different points, I am not sure which parts of which Modules I need to add code.

我遇到的问题是,鉴于工作簿名称/工作表名称发生变化,我无法弄清楚如何将这些工作簿中的每一个变暗。此外,随着新工作簿在不同时间点打开,我不确定需要添加代码的模块的哪些部分。

回答by VBA Pete

You can for example do the following to dim books and sheets:

例如,您可以执行以下操作来使书籍和纸张变暗:

First you need declares the workbooks:

首先,您需要声明工作簿:

Dim wbBook1 As Workbook
Dim wbBook2 As Workbook

Then you need to set each workbook (note that the second book is being opened while set:

然后您需要设置每个工作簿(请注意,设置时正在打开第二本书:

Set wbBook1 = ThisWorkbook
Set wbBook2 = Workbooks.Open("C:\PERSONAL_FOLDER\test.xlsm")

In order to identify which sheets are you working with, you need to declare and set these as well:

为了确定您正在使用哪些工作表,您还需要声明和设置这些:

Dim wsSheet1 As Worksheet
Dim wsSheet2 As Worksheet
Set wsSheet1 = wbBook1.Worksheets("Sheet1")
Set wsSheet2 = wbBook2.Worksheets("Sheet1")

Using wsSheet1 and wsSheet2 you can easily run macros that do something in your current workbook in sheet 1 and in workbook test in sheet 1.

使用 wsSheet1 和 wsSheet2,您可以轻松地运行在当前工作簿中的工作簿 1 和工作簿测试中的工作簿中执行某些操作的宏。

Once you are done using workbook test you can close it with the following command:

使用工作簿测试完成后,您可以使用以下命令关闭它:

wbBook2.close 

I hope this helps!

我希望这有帮助!