[英]VBA Object required error depending on code arrangement
r = mainWS.Cells(count, 1).Value
paths = mainWS.Cells(i, 2).Value
pathd = mainWS.Cells(i, 6).Value
.....
If (r = "H") Then
Application.Workbooks.Open (pathd & "\" & filed)
Set dWB = Application.Workbooks(filed)
Set tabD_WB = dWB.Sheets(tabd & "")
Application.Workbooks.Open (paths & "\" & files)
Set sWB = Application.Workbooks(files)
Set tabS_WB = sWB.Sheets(tabs & "")
End If
Set uRange = tabD_WB.Range(Cells(1, 1), Cells(5, tabD_WB.UsedRange.Columns.count))
So, if I put the last line starting with Set uRange inside the IF block the exercise works perfectly. 因此,如果我将以Set uRange开头的最后一行放在IF块内,则该练习将完美进行。 If I place it immediately afterwards/outside, it doesn't. 如果我在之后/外部立即放置它,则不会。 Can you help me understand why? 你能帮我理解为什么吗?
The error I get (if it's outside) is Object required
. 我得到的错误(如果在外面)是Object required
。 Is this some mistake of Excel inner workings? 这是Excel内部工作方式的某些错误吗?
I'm puzzled. 我很困惑 Thanks a lot! 非常感谢!
Why would you expect it to work when tabD_WB
is referred to outside of the IF
statement? 当在IF
语句之外引用tabD_WB
时,为什么会期望它起作用?
Unless you have more code that you're not showing us, you only set tabD_WB
inside the IF
statement, meaning the object is empty if r <> "H"
, and you can't access the range of an empty object. 除非您有更多没有向我们展示的代码,否则您只能在IF
语句中设置tabD_WB
,这意味着如果r <> "H"
,则该对象为空,并且您将无法访问空对象的范围。
You can write your code 您可以编写代码
Application.Workbooks.Open (pathd & "\" & filed)
Set dWB = Application.Workbooks(filed)
Set tabD_WB = dWB.Sheets(tabd & "")
as 如
Set dWB = Application.Workbooks.Open(pathd & "\" & filed)
Set tabD_WB = dWB.Sheets(tabd)
Now regarding your error, you have not fully qualified your Cells() object. 现在,关于您的错误,您还没有完全限定Cells()对象。 Try this 尝试这个
With tabD_WB
Set uRange = .Range(.Cells(1, 1), .Cells(5, .UsedRange.Columns.Count))
End With
I hope you have declared uRange
as a Range
somewhere in your code? 我希望您在代码中的某个位置声明uRange
为Range
? Also if the IF condition is not true then there will be no workbooks object? 另外,如果IF条件不成立,那么将没有工作簿对象吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.