打开两个工作簿时(虽然不是必需的),我想运行一个宏,它将宏从第一张表中的原始数据复制到同一工作簿的另一张表中,并将另一组原始数据从第一张表中复制到第三张纸来自另一本工作簿。
第一部分(从同一工作簿的一张纸复制到另一张纸)很好。但是,当我键入新代码以复制到另一个工作簿时,就会出现问题。当前错误是“运行时错误'13'类型不匹配”
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Set rawData = Workbooks.Open("D:\Work\Framas\CrusherRoom_V10_Test.xlsm")
Set materialStock = Workbooks.Open("D:\Work\Framas\MaterialStock_V01_Test.xlsm")
Set copySheet = rawData.Worksheets("VIE Screen")
Set pasteSheet = rawData.Worksheets("Crusher tracking")
Set pasteSheet2 = materialStock.Worksheets("Sheet1")
copySheet.Select
If Range("F23").Value = "OK" Then
Range("B7").Select
Selection.Copy
Range("O9").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B7").Select
Selection.Copy
Range("O18").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
copySheet.Range("O9:AR9").Copy
pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
' Copy to another sheet begins from here
copySheet.Range("O18:AG18").Copy
pasteSheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
End If
答案 0 :(得分:0)
VBA的第一个规则是“从不使用选择”
这是您的代码被重写
Option Explicit
Sub ts()
Dim rawData As Workbook
Dim materialStock As Workbook
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Dim pasteSheet2 As Worksheet
Set rawData = Workbooks.Open("D:\Work\Framas\CrusherRoom_V10_Test.xlsm")
Set materialStock = Workbooks.Open("D:\Work\Framas\MaterialStock_V01_Test.xlsm")
Set copySheet = rawData.Worksheets("VIE Screen")
Set pasteSheet = rawData.Worksheets("Crusher tracking")
Set pasteSheet2 = materialStock.Worksheets("Sheet1")
If copySheet.Range("F23").Value = "OK" Then
'as written this code copies cells in whichever sheet is active - you should specify which sheet you mean
Range("O9").Formula = Range("B7").Value
Range("O18").Formula = Range("B7").Value
' Copy to another sheet begins from here
copySheet.Range("O9:AR9").Copy
pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
'copy to another workbook starts here
copySheet.Range("O18:AG18").Copy
pasteSheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial lPasteValues
End If
End Sub
我目前看不到任何问题-但是我没有您的文件。要点:始终使用Option Explicit,始终定义变量。 如果使用F8单步执行此代码,则可以看到引发错误的行。可能是工作表名称中的错字-工作簿是否真正打开?