我的错误是什么设置? 这个小组在完全不同的工作簿中运行
在Set wb1线上接收到“运行时错误9,下标超出范围”。 这种类似的结构在不同的工作簿中运行正常,没有错误。
我的目标是将源文档中的单元格复制到目标文档中。
Sub CopySheetsl() Dim wb As Workbook, wb1 As Workbook Dim LastRow As Long Set wb = Workbooks("C:\Test\DST.xlsm") Set wb1 = Workbooks.Open("C:\Test\Source.xlsx") wb1.Sheets("SourceNamedSheet").Range("A1") = wb.Sheets("DestinationNamedSheet").Range("A1").Value wb1.Close End Sub
为更加健壮的方法来处理工作簿,您可能需要使用以下GetOrSetWorkbook()
函数:
Option Explicit Function GetOrSetWorkbook(wbName As String) As Workbook On Error Resume Next Set GetOrSetWorkbook = Workbooks(GetNameOnly(wbName)) '<--| check if a workbook with given name is already open If GetOrSetWorkbook Is Nothing Then Set GetOrSetWorkbook = Workbooks.Open(wbName) '<--| if no workbook open with given name then try opening it with full given path End Function
它使用下面的帮助器 GetNameOnly()
函数:
Function GetNameOnly(pathStrng As String) As String Dim iSlash As Long iSlash = InStrRev(pathStrng, "\") If iSlash > 0 Then GetNameOnly = Mid(pathStrng, iSlash + 1, Len(pathStrng)) Else GetNameOnly = pathStrng End If End Function
所以可能的用途是:
Option Explicit Sub CopySheetsl() Dim wb As Workbook, wb1 As Workbook Dim LastRow As Long Set wb = GetOrSetWorkbook("C:\Test\DST.xlsm") '<--| try getting "C:\Test\DST.xlsm" If wb Is Nothing Then '<--| if unsuccessful... '... code to handle C:\Test\DST.xlsm workbook error, like: MsgBox "Couldn't find 'C:\Test\DST.xlsm' !", vbCritical + vbOKOnly End If Set wb1 = GetOrSetWorkbook("C:\Test\Source.xlsx") '<--| try getting "C:\Test\Source.xlsx If wb Is Nothing Then '<--| if unsuccessful... '... code to handle 'C:\Test\Source.xlsx' workbook error, like: MsgBox "Couldn't find 'C:\Test\Source.xlsx'!", vbCritical + vbOKOnly End If 'here goes rest of the code to be executed once all necessary workbooks have been properly set wb1.Sheets("SourceNamedSheet").Range("A1") = wb.Sheets("DestinationNamedSheet").Range("A1").Value wb1.Close End Sub
当然也可以用工作表假设一个非常相似的GetOrSet方法。
如果DST.xlsm
已经打开了
Set wb = Workbooks("DST.xlsm")
DST.xlsm
如果您需要打开DST.xlsm
Set wb1 = Workbooks.Open("C:\Test\DST.xlsm")