gpt4 book ai didi

vba - 如果工作簿和工作表未处于事件状态,则无法使用范围

转载 作者:行者123 更新时间:2023-12-04 21:24:08 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com