我正在编写一个将遍历一批文件的宏,询问目标文件的名称以及来源。它将从源复制,然后粘贴到目标。我计划构建一个userform来收集所有名称并将它们链接到源。这将在循环中发生,因此我创建了一个子程序作为参数的两个变量,它将遍历它们来进行复制和粘贴。这只是我的第二个宏,所以任何评论都表示赞赏。
第Set wsCopyFrom = wbCopyFrom.Worksheets(sheetName)
行给了我一个'运行时错误'''需要的对象'
但是,当我将其移动到我的代码的不同部分时,它会给我一个不同的错误'错误9,下标超出范围
这是我认为导致错误的部分。
Sub copyTo(arr_Destination As Variant, arr_Source As Variant)
For Each fileName In arr_Destination
For Each sheetName In arr_Source
MsgBox sheetName
Set wsCopyFrom = wbCopyFrom.Worksheets(sheetName)
wsCopyFrom.Range("B5:V18").Copy
wsCopyTo.Range("A9").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Next sheetName
Next fileName
End Sub
这是我调用子程序只是为了澄清的部分。
Sub CommandButton1_Click()
Dim vFile As Variant
Dim wbCopyTo As Workbook
Dim wsCopyTo As Worksheet
Dim wbCopyFrom As Workbook
Dim wsCopyFrom As Worksheet
'Sheet Name array
Dim sm As Variant
Dim sheetName As Variant
Dim fileName As Variant
'Ranges Arrays
Dim copyFrRg As Variant
Dim copyToRg As Variant
Set wbCopyTo = ActiveWorkbook
Set wsCopyTo = ActiveSheet
'-------------------------------------------------------------
'Open file with data to be copied
vFile = Application.GetOpenFilename("Excel Files (*.xl*)," & _
"*.xl*", 1, "Select Excel File", "Open", False)
'If Cancel then Exit
If TypeName(vFile) = "Boolean" Then
Exit Sub
Else
Set wbCopyFrom = Workbooks.Open(vFile)
End If
'--------------------------------------------------------------
'Sheet array(s)
sm = Array("Subm CT by UW Monthly - WD", "Subm Ratio by UW - WD")
MsgBox sm(1)
Dim fArr()
fArr = Array(wbCopyFrom.Name)
MsgBox fArr(0)
Call copyTo(fArr, sm)
wbCopyFrom.Close SaveChanges:=False
Exit Sub
End Sub