我尝试使用VBA将单元格值从一个excel复制到另一个excel。我要做的是通过单击脚本,excel(不打开)值会自动从一个工作表复制到另一个工作表。在执行我的脚本时,我收到错误,其中显示类型不匹配:'表格'。我已经阅读过各种帖子,但找不到这个问题的答案。我的脚本看起来像这样:
ImportData_Click
Sub ImportData_Click()
Dim objExcel2
Set objExcel2 = CreateObject("Excel.Application")
' open the source workbook and select the source sheet
objExcel2.Workbooks.Open "<path>\test1_vbs.xlsx"
' copy the source range
Sheets("Sheet1").Range("A1:B2").Copy
' select current workbook and paste the values
ThisWorkbook.Activate
Sheets("Sheet2").Range("A1:B2").PasteSpecial xlPasteValues
' close the source workbook
Windows("<path>\test1_vbs.xlsx").Activate
ActiveWorkbook.Save
ActiveWorkbook.Close
End Sub
答案 0 :(得分:0)
如果您要仅在应用程序实例之间传输值,请跳过剪贴板并使用数组。
Option Explicit
Sub ImportData_Click()
Dim objExcel2 As Object, arr As Variant
Set objExcel2 = CreateObject("Excel.Application")
' open the source workbook and select the source sheet
With objExcel2.Workbooks.Open("c:\test\test2_vbs.xlsx")
' copy the source range to variant array
arr = .Worksheets("Sheet1").Range("A1:B2").Value
' close the source workbook
.Close savechanges:=False
End With
' select current workbook and paste the values
ThisWorkbook.Worksheets("Sheet2").Range("A1").Resize(UBound(arr, 1), UBound(arr, 2)) = arr
' close the source application instance
objExcel2.Quit
Set objExcel2 = Nothing
ActiveWorkbook.Save
ActiveWorkbook.Close
End Sub