使用多个工作簿和宏 - 调用工作簿? [VBA]

时间:2016-04-06 20:51:25

标签: excel vba excel-vba macros

我可能有一个简单的问题,但我无法弄清楚出了什么问题。我正在尝试在excel中创建一个可以对多个文件执行多项操作的宏。背景信息:

我正在运行Macro的excel表位于其自己的文件夹中。我已经设置了一个具有这种结构的小测试文件夹: C:\ Users \ schris \ Desktop \ Eprime Testing \

  • 此文件夹中包含两个文件夹:

    • \ Master Dataset \

      • 在此文件夹中,带有宏的excel文件为
    • \ Eprime Processing \

      • 此文件夹中有三个文件夹,名为“Fear”,“Gender”和“Happy”。在每个文件夹中都有一个我希望打开的Excel文件。

我想要做的是创建一个可以调用其他各种潜艇的Sub RunAll,因为我希望宏可以做很多不同的事情,我想让它保持井井有条。

所以:

Sub RunAll()
Call OpenWorkbooks
Call ProcessFear
Call ProcessGender
Call ProcessHappy

End Sub

这是我的OpenWorkbooks代码:

Sub OpenWorkbooks()
Dim wb1 As Workbook
Dim wbFear As Workbook
Dim wbGender As Workbook
Dim wbHappy As Workbook
Dim FileToOpen As Variant
Dim FileToOpen2 As Variant
Dim FileToOpen3 As Variant
Dim Sheet As Worksheet

' Must be workbook with the Macros I'm running
Set wb1 = ActiveWorkbook

' Opens Fear
ChDir "C:\Users\schris\Desktop\Eprime Testing\Eprime Processing\Fear"

FileToOpen = Application.GetOpenFilename _
(Title:="Please choose Fear file")

If FileToOpen = False Then
    MsgBox "No File Specified.", vbExclamation, "ERROR"
    Exit Sub
Else
    Set wbFear = Workbooks.Open(fileName:=FileToOpen)
End If

Set wbFear = ActiveWorkbook

' Opens Gender
ChDir "C:\Users\schris\Desktop\Eprime Testing\Eprime Processing\Gender"

FileToOpen2 = Application.GetOpenFilename _
(Title:="Please choose Gender file")

If FileToOpen2 = False Then
    MsgBox "No File Specified.", vbExclamation, "ERROR"
    Exit Sub
Else
    Set wbGender = Workbooks.Open(fileName:=FileToOpen2)
End If

Set wbGender = ActiveWorkbook

' Opens Happy
ChDir "C:\Users\schris\Desktop\Eprime Testing\Eprime Processing\Happy"

FileToOpen3 = Application.GetOpenFilename _
(Title:="Please choose Happy file")

If FileToOpen3 = False Then
    MsgBox "No File Specified.", vbExclamation, "ERROR"
    Exit Sub
Else
    Set wbHappy = Workbooks.Open(fileName:=FileToOpen3)
End If

Set wbHappy = ActiveWorkbook
End Sub

现在我希望能够引用这三个工作簿(wbFear,wbGender,wbHappy)并在它们之间无缝移动。在Sub OpenWorkbooks()中进行测试时,wbFear.Activate可以正常工作和处理......但是当我分离出每个宏的任务时(即OpenWorkbooks现在只打开工作簿,ProcessFear只处理恐惧中的数据)我得到一个运行时错误'91':对象变量或没有设置块变量。

我假设这与声明的工作簿名称在切换Subs时“丢失”有关,但是当我将OpenWorkbooks中的代码放入RunAll并且只运行ProcessFear时,它仍然无法激活的工作簿。

基本上,我的问题是:

如何让一个宏打开三个工作簿,并将它们全部声明为其他宏可以引用的内容?我需要完成很多任务,所以我真的希望每个都有单独的Subs,这样我就不会迷失在代码中。

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

有更好,更优雅的解决方案。但这是最简单,也是最容易实现的。声明3个全局对象变量以保存工作簿引用。打开工作簿并在OpenWorkbooks中分配这些变量。根据需要使用它们。关闭它们并在新程序Nothing中将它们设置为CloseWorkbooks。 (在此上下文中不需要Call

Public gwbFear as WorkBook
Public gwbGender as WorkBook
Public gwbHappy as WorkBook

Sub RunAll()
    OpenWorkbooks
    ProcessFear
    ProcessGender
    ProcessHappy
    CloseWorkbooks
End Sub