我创建了一些VBA代码,用于从名为" Horizontal Data"的电子表格中获取填充数据。并将其粘贴到名为"主计划数据"的工作表中,但是使用Workbooks(wb1)会导致类型不匹配错误,我在这里做错了吗?
Dim WBA as Variant
Dim WB1, WB2 As Workbook
Dim L As Long
Set WB2 = ThisWorkbook
MsgBox "Select Master Plan File"
WBA = Application.GetOpenFilename( _
FileFilter:="Excel Files (*.XLSX), *.XLSX", _
Title:="Select Master Plan File")
If WBA = False Then
MsgBox "You have not selected a file"
Exit Sub
End If
Set WB1 = Workbooks.Open(WBA)
WB2.Activate
With Worksheets("Master Plan Data")
.Rows("2:100000").Clear
End With
'ERROR BEGINS HERE
With Workbooks(WB1) ' <-- Getting Type Mismatch here
Worksheets("HORIZONTAL_DATA").Cells.Select
Selection.Copy
End With
答案 0 :(得分:3)
Workbooks
对象当然可以用于查找工作簿。但是,它需要数字索引或工作簿名称本身:
Workbooks(42)
Workbooks("paxsheet.xls")
您已经拥有您要使用的工作簿,它位于WB1
,所以您不需要去寻找它。
所以改变:
With Workbooks(WB1) ' <-- Getting type mismatch here '
成:
With WB1 ' <-- Should not get type mismatch here '
一切都应该好。
并且超出即时错误,因为您要使用工作簿中的工作表,您需要通过在其前面添加.
来指定:
With WB1
.Worksheets("HORIZONTAL_DATA").Cells.Select
Selection.Copy
End With
此外,假设您不需要为该副本维护选择,您可以直接复制而不首先选择:
With WB1
.Worksheets("HORIZONTAL_DATA").Cells.Copy
End With
但是,当然,即使使用with
也变得毫无用处,所以你可能只想简化整个事情:
WB1.Worksheets("HORIZONTAL_DATA").Cells.Copy