运行时错误 438:对象不支持此属性或方法 (VBA)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40141765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run-time error 438: Object doesn't support this property or method (VBA)
提问by mrbusto71
This is driving me absolutely insane. I'm new to VBA and I compiled code line by line, adding more and more verifying it all worked within the same workbook using F8. The last bit I have to add is just opening a separate workbook, and now it's giving me errors each time. Here's my code:
这让我完全疯了。我是 VBA 的新手,我逐行编译了代码,添加了越来越多的验证,以使用 F8 在同一个工作簿中进行验证。我必须添加的最后一点只是打开一个单独的工作簿,现在它每次都给我错误。这是我的代码:
Sub MasterXfer()
Dim mystring As String, wbName As String, dt As String, sdt As String, ldt As String
Dim wb1 As Workbook, wb2 As Workbook, mypath As String
wbNam = "Productivity "
dt = Sheet1.Range("B1").Value
sdt = Format(CStr(dt), "m.d.yy") & ".xlsx"
ldt = Format(CStr(dt), "yyyy") & "\" & Format(CStr(dt), "mm") & "_" & MonthName(Month(dt)) & "_" & Year(dt)
mypath = "S:\" & ldt & "\" & wbNam & sdt
Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Open(mypath) 'HERE'S WHERE IT ERRORS OUT
With wb1
lastrow = Worksheets(1).Range("A" & Rows.Count).End(xlUp).Row
For x = 2 To lastrow Step 16
mystring = .Range("A" & x)
Stepping through this, it works fine. Then I get to the Set wb2 = Workbooks.Open
line, and it successfully opens the target workbook, however immediately upon opening it the code stops and the error in question comes up.
通过这一步,它工作正常。然后我到达该Set wb2 = Workbooks.Open
行,它成功地打开了目标工作簿,但是一旦打开它,代码就会立即停止并且出现有问题的错误。
If anyone at all can tell me what mistake I'm making I will name my firstborn after you.
如果有人能告诉我我犯了什么错误,我会以你的名字命名我的长子。
回答by
Your error if caused by this line mystring = .Range("A" & x)
. Workbook
does not have a Range
method. You need to change it to wb1.Worksheets(1)
.
你的错误是由这条线引起的mystring = .Range("A" & x)
。 Workbook
没有Range
方法。您需要将其更改为wb1.Worksheets(1)
.
You should also test if the file exists before opening it.
您还应该在打开文件之前测试该文件是否存在。
I included an alternate method of creating your file string using the backslash to escape characters in the Format
functions Format
parameter.
我在Format
函数Format
参数中包含了使用反斜杠创建文件字符串的另一种方法来转义字符。
Sub MasterXfer()
Dim wb2 As Workbook
Dim mypath As String
mypath = Format(Sheet1.Range("B1").Value, "\S:\YYYY\MM_MMMM_YYYY\Pro\du\ctivit\y MM.DD.YY.xl\sx")
If Len(Dir(mypath)) = 0 Then
MsgBox "File not found" & vbCrLf & mypath
Stop
Exit Sub
End If
Set wb2 = Workbooks.Open(mypath)
With ThisWorkbook.Worksheets(1)
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For x = 2 To LastRow Step 16
mystring = .Range("A" & x)
Next
End With
End Sub