以下代码:
Sub CopyData()
Dim Wb1 As Workbook, wb2 As Workbook
For Each wB In Application.Workbooks
If Left(wB.Name, 21) = "Open Order Monitoring" Then
Set Wb1 = wB
Exit For
End If
Next
Set wb2 = ThisWorkbook
Wb1.Sheets(1).Range("A2").Range(.Cells(1, 1), .End(xlDown).Cells(1, 39)).Copy wb2.Sheets(2).Range("B5")
End Sub
宏应该从具有变量名称的打开工作簿中复制数据(打开订单监控[...])并粘贴到我运行宏的工作簿的第二张表中。
但是这句话:
Wb1.Sheets(1).Range("A2").Range(.Cells(1, 1), .End(xlDown).Cells(1, 39)).Copy wb2.Sheets(2).Range("B5")
给了我一个错误。有人可以解决这个问题吗?
答案 0 :(得分:3)
自:
使用完全限定的范围引用(直到工作簿和工作表)更安全。特别是当您处理多个工作簿和/或工作表时
如果您只对粘贴值感兴趣,那么使用Range1.value = Range2.Value
代替.Copy()
对象的Range
方法会更快(也更安全)。
然后,下面是一个可能的代码:
Option Explicit
Sub CopyData()
Dim Wb1 As Workbook, wb2 As Workbook, wB As Workbook
Dim rngToCopy As Range
For Each wB In Application.Workbooks
If Left(wB.Name, 21) = "Open Order Monitoring" Then
Set Wb1 = wB
Exit For
End If
Next
If Not Wb1 Is Nothing Then '<~~ check if you actually found the needed workbook
Set wb2 = ThisWorkbook
With Wb1.Sheets(1)
Set rngToCopy = .Range("A2:AM2", .Cells(.Rows.Count, "A").End(xlUp))
End With
wb2.Sheets(2).Range("B5:AN5").Resize(rngToCopy.Rows.Count).Value = rngToCopy.Value
End If
End Sub
答案 1 :(得分:1)
请尝试使用以下代码
Sub CopyData()
Dim Wb1 As Workbook, wb2 As Workbook, wb As Workbook
Set wb2 = ThisWorkbook
For Each wb In Workbooks
If Left(wb.Name, 21) = "Open Order Monitoring" Then
Set Wb1 = wb
Exit For
End If
Next
Wb1.Sheets(1).Range("A2:AM2").Copy wb2.Sheets(2).Range("B5") 'Edited here
End Sub