运行时错误438:对象不支持此属性或方法(VBA)

这让我绝对疯了。 我是VBA的新手,我逐行编译代码,使用F8添加越来越多的validation工作。 我必须添加的最后一点是打开一个单独的工作簿,现在它每次都给我错误。 这是我的代码:

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), "mdyy") & ".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) 

通过这个,它工作正常。 然后我进入Set wb2 = Workbooks.Open行,它成功地打开了目标工作簿,但是立即打开它的代码停止,出现错误。

如果任何人都可以告诉我我犯了什么错误,我会在你后面命名我的长子。

如果由此行引起的错误mystring = .Range("A" & x)Workbook没有Range方法。 您需要将其更改为wb1.Worksheets(1)

打开文件之前,还应该testing文件是否存在。

我包括一个替代方法创build您的文件string使用反斜杠转义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