如果工作簿和工作表未处于活动状态,则无法使用范围

nwh*_*ght 1 excel vba excel-vba

当我尝试将值从一个工作簿导入另一个工作簿时,我收到应用程序或对象定义的错误.我已经能够通过显式激活工作簿并在引用每个工作表之前选择工作表来解决它,但我想尽可能避免这种情况.这两个工作簿在代码中都是打开的.有什么想法吗?

这会给我带来错误:

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
Run Code Online (Sandbox Code Playgroud)

这很好,但我想避免.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
Run Code Online (Sandbox Code Playgroud)

在我调试时,看起来wbReceive.Sheets(sExcept)行中引用的单元实际上引用了wbReceive工作簿中的不同工作表.不知道为什么会出现这种情况,因为wb和表格是明确引用的?

Tim*_*ams 5

Set rExceptions = wbImport.Sheets(sSht).Range(Cells(rCell.Row, iHeadCol), _
                                              Cells(rCell.Row, iLastCol))
Run Code Online (Sandbox Code Playgroud)

您已获得资格Range,但不是Cells:如果未通过特定工作表进行限定,则会引用ActiveSheet.有点违反直觉,(合格)包装Range不会"哄骗"......

试试这个:

With wbImport.Sheets(sSht)
    Set rExceptions =  .Range(.Cells(rCell.Row, iHeadCol), _
                              .Cells(rCell.Row, iLastCol))
End with
Run Code Online (Sandbox Code Playgroud)