这让我绝对疯了。 我是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)
单步执行此操作,它可以正常工作。然后我到达Set wb2 = Workbooks.Open
行,它成功打开了目标工作簿,但是一旦打开它,代码就会停止并且出现问题。
如果有人可以告诉我我犯了什么错误,我会在你之后命名我的长子。
答案 0 :(得分:1)
由此行mystring = .Range("A" & x)
引起的错误。 Workbook
没有Range
方法。您需要将其更改为wb1.Worksheets(1)
。
您还应该在打开文件之前测试该文件是否存在。
我提供了一种使用反斜杠创建文件字符串的替代方法,以转义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