我使用另一个工作簿中的活动工作表在我的工作簿中创建了一个宏。我现在想运行我的宏,但使用另一个不同的活动工作簿来获取我的数据。
在我的宏中我有20次这条线......
窗( “IFS_round_1”)。激活
...每次打开新工作簿运行宏时,我都不想更改它(例如IFS_round_2)。有什么我可以添加,所以宏只使用我打开的活动工作簿?
谢谢!
答案 0 :(得分:0)
创建一个变量来引用工作簿。例如:
Sub Macro1()
Dim wb as Workbook
Set wb = ActiveWorkbook
wb.Activate
'DO CODE HERE
End Sub
这有帮助吗?
答案 1 :(得分:0)
我不知道您是否以编程方式打开其他工作簿,但此解决方案有效。基本上,只要打开它就可以将句柄保存到其他工作簿中。
sother_filename = "IFS_round_1"
'saves the name of the current workbook
curr_workbook = ActiveWorkbook.Name
'opens the new workbook, this automatically returns the handle to the other
'workbook (if it opened it successfully)
other_workbook = OpenWorkbook(sother_filename)
但有趣的是什么?还有一个解决方案,可以在只打开两个工作簿时自动获取工作簿名称,然后只需使用它来调用其他工作簿
Function GetOtherWBName()
GetOtherWBName = ""
'if we dont have exactly two books open
'we don't know what to do, so just quit
If (Workbooks.Count) <> 2 Then
Exit Function
End If
curr_wb = ActiveWorkbook.Name
'if the active workbook has the same name as workbook 1
If (StrComp(curr_wb, Workbooks(1).Name) = 0) Then
'then the other workbook is workbook 2
GetOtherWBName = Workbooks(2).Name
Else
'then this is the other workbook
GetOtherWBName = Workbooks(1).Name
End If
End Function
所以现在在具有宏的工作簿中创建一个按钮并为其分配一个类似于此
的宏Sub ButtonClick()
'first we save the current book, so we can call it easily later
curr_wb = ActiveWorkbook.Name
other_wb = GetOtherWBName()
If Len(other_wb) = 0 Then
MsgBox ("unable to get other wb")
Exit Sub
End If
'now to call the other workbook just use
Workbooks(other_wb).Activate
'all the rest of your code
End Sub