尝试使用2个工作簿作为对象时出现ByRef错误

时间:2017-06-29 02:10:39

标签: vba excel-vba excel

我需要使用2个工作簿对象在我的宏中运行第二个子。但是,我设置的第一张纸似乎总是存在ByRef错误。我在下面提出了一个例子。我定义对象错了吗?

Sub test1()
Dim inputwb, outputwb As Workbook

'sets current workbook as inputwb
Set inputwb = ThisWorkbook '<---this sheet causes the ByRef error

'open 2nd workbook
Workbooks.Open (filepath & "\" & filename)
'sets 2nd workbook as outputwb
Set outputwb = ActiveWorkbook

'call next sub
Call test2(inputwb, outputwb)

End Sub

Sub test2(wb1 As Workbook, wb2 As Workbook)

MsgBox ("done!")

End Sub

1 个答案:

答案 0 :(得分:3)

Dim变量没有As type子句时,默认设置为Variant。尝试将Variant作为参数传递给期望Workbook的函数/子例程将导致错误。

因此,请从

更改Dim声明
Dim inputwb, outputwb As Workbook

Dim inputwb As Workbook, outputwb As Workbook