【发布时间】:2014-12-18 10:18:36
【问题描述】:
我有一个 Book1.xls Excel 工作簿,其中编写了一个宏,以便在 workbook open 上运行宏。 此宏获取工作簿路径中的所有 CSV 文件并将所有 CSV 合并到一个工作表中,例如 Master.xlsx,它可以正常工作并创建 Master.xlsx。 在这个宏的末尾,我调用了在同一张表的模块中编写的另一个宏,并将 Master.xlsx 引用作为工作簿参数传递给另一个宏
现在我想要的是我需要将 Master.xlsx 传递给这个宏(模块)的参数设置为 current/active 工作簿,以便我可以格式化 master.xlsx 的内容
我的 Book1.xls 代码是:
Private Sub Workbook_Open()
'Create Excel application instance
Dim xlApp As Object
Dim dt, masterpath, folderPath, fileName, dtFolder As String
Set xlApp = CreateObject("Excel.Application")
'Setup workbooks
Dim wb As Excel.Workbook
Dim wBM As Excel.Workbook
Dim Wk As Workbook
fileName = "C:\Master.xlsx"
'Create a new Workbook
Set Wk = Workbooks.Add
Application.DisplayAlerts = False
Wk.SaveAs fileName:=fileName
Wk.Close SaveChanges:=False
Application.DisplayAlerts = True
'Csv files folder
Dim CSVfolder As String
CSVfolder = masterpath
'Master Excel file path
Dim mF As String
mF = fileName 'Where your master file is
'open the master file
Set wBM = xlApp.Workbooks.Open(mF)
'search and open the client files
Dim fname As String
fname = Dir(CSVfolder & "\*.csv")
Do While fname <> ""
'open the client file
Set wb = xlApp.Workbooks.Open(CSVfolder & "\" & fname)
'copy the first sheet from client file to master file
wb.Sheets(1).Copy After:=wBM.Sheets(wBM.Sheets.count)
'save master file
wBM.Save
'close client file
wb.Close False
'move to next client file
fname = Dir()
Loop
xlApp.Visible = True
Set xlApp = Nothing
Call AnotherMacroInModuleOfSameWorkbook(wBM)
End Sub
同一工作簿模块中的宏代码
Sub AnotherMacroInModuleOfSameWorkbook(wb As Workbook)
wb.Activate
MsgBox (wb.Name)
MsgBox (ActiveWorkbook.Name)
End Sub
这里我得到 警报 1 的“Master.xlsx”和 警报 2 的“Book1.xls”
我想要的是,因为我从上面的宏中传递了 Master.xlsx 的引用,然后在下面的宏中激活了 Master.xlsx,所以警报 2 应该将“Master.xlsx”作为警报。
请帮忙。
谢谢。
【问题讨论】:
-
一个细节:你可能想要
Dim dt As String, masterpath As String, ... As String而不是Dim dt, masterpath, ... As String。 -
@sancho.s :正如我所说,第一个宏正在正常运行并生成 Master.xlsx。因此,您指出的上述语法错误无效。一切正常。您似乎误读了我的问题,我在引用由第二个宏中的第一个宏生成的新工作表时遇到了问题。即我无法将作为工作簿对象从调用宏传递到被调用宏的 Master.xlsx 引用。谢谢。
-
你的发现对我来说也很奇怪。尝试一下:在
wb.Activate放置一个断点,然后运行您通常的宏序列。执行中断后,在立即窗口中执行? wb.Name, ActiveWorkbook.Name,然后再逐步遍历接下来的 3 行中的每一行。您可能会在那里找到答案。 -
在 'wb As Workbook' 中使用其他变量代替变量 'wb' 并尝试使用 'mwb as WorkBook'。
-
@PareshJ :试过但没用。这里的问题是工作簿没有被激活。 MsgBox (wb.Name) wb.Activate MsgBox (ActiveWorkbook.Name) 。第一个警报说“Master.xlsx”,第二个说“Book1.xlsx”,即使在激活 Master.xlsx 之后也是如此