作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这个问题在这里已经有了答案:
Excel VBA, getting range from an inactive sheet
(3 个回答)
2年前关闭。
当我尝试将值从一个工作簿导入到另一个工作簿时,出现应用程序或对象定义错误。我已经能够通过在引用每个工作簿的范围之前显式激活工作簿并选择工作表来解决它,但如果可能的话,我想避免这种情况。此时代码中的两个工作簿都是打开的。有什么想法吗?
这会为我产生错误:
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 和 sheet 被明确引用?
最佳答案
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
关于vba - 如果工作簿和工作表未处于事件状态,则无法使用范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28861117/
我是一名优秀的程序员,十分优秀!