作者:尛爱总_305 | 来源:互联网 | 2023-05-19 14:01
当我尝试将值从一个工作簿导入另一个工作簿时,我收到应用程序或对象定义的错误.我已经能够通过显式激活工作簿并在引用每个工作表之前选择工作表来解决它,但我想尽可能避免这种情况.这两个工作簿在代码中都是打开的.有什么想法吗?
这会给我带来错误:
Dim wbImport As Workbook
Dim wbReceive As Workbook
Const sExcept = "Sheet2 Name"
Const sSht = "Sheet1 Name"
Dim rExceptions As Range
wbReceive.Sheets(sExcept).Rows(1).Insert shift:=xlDown
Set rExceptiOns= wbImport.Sheets(sSht).Range(Cells(rCell.Row, iHeadCol), Cells(rCell.Row, iLastCol))
wbReceive.Sheets(sExcept).Range(Cells(1, iHeadCol), Cells(1, iLastCol)).Value = rExceptions.Value 'error occurs here
这很好,但我想避免.Select
和.Activate
wbReceive.Sheets(sExcept).Rows(1).Insert shift:=xlDown
wbImport.Activate
wbImport.Sheets(sSht).Select
Set rExceptiOns= wbImport.Sheets(sSht).Range(Cells(rCell.Row, iHeadCol), Cells(rCell.Row, iLastCol))
wbReceive.Activate
wbReceive.Sheets(sExcept).Select
wbReceive.Sheets(sExcept).Range(Cells(1, iHeadCol), Cells(1, iLastCol)).Value = rExceptions.Value
在我调试时,看起来wbReceive.Sheets(sExcept)
行中引用的单元实际上引用了wbReceive
工作簿中的不同工作表.不知道为什么会出现这种情况,因为wb和表格是明确引用的?
1> Tim Williams..:
Set rExceptiOns= wbImport.Sheets(sSht).Range(Cells(rCell.Row, iHeadCol), _
Cells(rCell.Row, iLastCol))
您已获得资格Range
,但不是Cells
:如果未通过特定工作表进行限定,则会引用ActiveSheet.有点违反直觉,(合格)包装Range
不会"哄骗"......
试试这个:
With wbImport.Sheets(sSht)
Set rExceptiOns= .Range(.Cells(rCell.Row, iHeadCol), _
.Cells(rCell.Row, iLastCol))
End with