VBA - excel关闭了打开新版本

时间:2017-04-06 14:48:52

标签: excel vba excel-vba

我有一个奇怪的问题,我怀疑它与Excel的版本有关,但我根本不确定。我无法独自解决这个问题,所以我需要你的帮助。我有一个宏,它在一个新的工作簿上运行 - 它没有保存在任何地方,因为工作人员将在之后手动保存它。宏是一个.xlam格式加载项,向功能区添加几个按钮,这些按钮启动代码。 在代码中,我有一个简单的行来打开一个新工作簿,用户先前选择:

Application.DisplayAlerts = False
    Set wbMPA = Workbooks.Open(MPA_file)
Application.DisplayAlerts = True

早些时候,代码将活动工作簿设置为宏将主要处理的对象/工作簿(尝试两个版本):

Set dwb = Application.ActiveWorkbook

以及稍后的代码

dwb.activate

OR:

dwb = ActiveWorkbook.Name

然后

workbooks(dwb).Activate

这些行位于单独的subs中,但变量是全局声明的。

代码工作正常,直到打开wbMPA(一直在本地观看)。当我尝试使用上面的代码打开新文件时,早期的工作簿(dwb)只是因为未知原因而关闭。 我从第一种方法得到的错误是这样的: error screenshot 第二个提供了一个简单的" Subscipt超出范围"。 然而,错误不是问题。问题在于它们的原因,这是因为未知原因而关闭了工作簿。

只有当我打开全新的工作簿(使用“开始”栏上的excel图标)时才会发生这种情况 - 当我从“文件”中执行此操作时 - >新 - >空白工作簿使用已打开的工作簿,不会发生错误。

另一件奇怪的事 - 我和我的工作同事使用2013版的Excel。我从来没有这个错误,每次都有。

这是代码的一般方案,在这种情况下其他事情毫无意义,因为没有其他操作工作簿/工作表。

Dim dwb As Object
Dim wbMPA As Object

Sub_1()

Set dwb = ActiveWorkbook
Set wbMPA = Workbooks.Open(MPA_file)

Call Sub_2

End Sub 


Sub_2()

dwb.Activate

End Sub

我在Sub_2中激活dwb时遇到错误,因为它关闭了自己,​​因为上帝知道在Sub_1中打开wbMPA的原因是什么。

1 个答案:

答案 0 :(得分:0)

If you have only opened a blank workbook (clicking Excel from Toolbar, for example) and then you open any named workbook before making any changes to the blank workbook, the blank workbook will disappear. I believe that is normal/expected behavior.

I can't speculate why this happens on one computer but not another, but this is always how I have observed new/blank documents (Excel, PowerPoint, Word) to behave, and assume this to be the normal behavior. You may have some different option/configuration on your Excel environment which is changing this default behavior, or maybe you are slightly altering the blank file before running the macro, and your co-worker isn't, etc.

A word of caution to avoid relying on ActiveWorkbook -- and especially in this case if the expectation is to always Set dwb to a new/blank workbook, the best way to do that is to explicitly create a new/blank workbook, rather than relying on the user to manually open a new/blank target workbook.

Set dwb = Workbooks.Add

If, on the other hand dwb must be assigned to some other known/existing workbook, then you should be either providing the file path to an Open statement, or the workbook name to the Workbooks collection.

On a related note, it's almost never necessary to Activate a workbook, see here:

How to avoid using Select in Excel VBA macros

And further note: your variables aren't globally scoped, they're scoped only to the module using Dim statement. A public declaration uses the Public keyword, not the Dim keyword. Both module-scoped and global-scoped should be used with caution (Public moreso than module-scoped) and in most cases it's preferable to pass objects/variables by reference to dependent subs and functions:

How to make Excel VBA variables available to multiple macros?