场景:Workbook2.xlsx,Workbook1.xlsx和VBA编辑器已打开。 Workbook1.xlsx和Workbook2.xlsx也是VBA项目,每个项目都有一个名为Sheet1(Sheet1)的活动工作表对象。
在Workbook2中单击CommandButton5时,我想将Workbook1中的单元格A1到D10移动到Workbook2的A1到D10。
当我在调试模式下将鼠标移动到“Set Move = ...”时,它表示Move = Nothing。
Private Sub CommandButton5_Click()
Dim Move As Range
Set Move = Workbooks(Workbook1).Worksheets(1).Range(Cells(1,1), Cells(4,10))
Move.Select
Selection.Copy
Workbooks(Workbook2).Worksheets(1).Range(Cells(1,1), Cells(4,10)).Select
ActiveSheet.Paste
End Sub
答案 0 :(得分:2)
您需要在工作簿的名称周围使用引号。 此外,为了使用工作簿(选择范围并进行复制和粘贴),您明确需要激活工作簿。
Private Sub CommandButton5_Click()
Dim Book As Workbook
' Get Workbook 1 and activate it
Set Book = Workbooks("Workbook1")
Book.Activate
Dim Move As Range
Set Move = Book.Worksheets(1).Range(Cells(1, 1), Cells(4, 10))
Move.Select
Selection.Copy
' Get Workbook 2 and activate it
Set Book = Workbooks("Workbook2")
Book.Activate
Set Move = Book.Worksheets(1).Range(Cells(1, 1), Cells(4, 10))
Book.Worksheets(1).Range(Cells(1, 1), Cells(4, 10)).Select
ActiveSheet.Paste
End Sub
另请注意,为了使用多个工作簿,必须在同一个Excel实例中打开它们(即在同一个Excel进程中运行)。如果在不同的Excel进程中打开了多个工作簿,则无法从同一个宏中访问它们。
以下是不需要使用剪贴板的变体:
Sub CommandButton5_Click()
Dim Source As Range
Workbooks("Workbook1").Activate
Set Source = Workbooks("Workbook1").Worksheets(1).Range(Cells(1, 1), Cells(4, 10))
Dim Target As Range
Workbooks("Workbook2").Activate
Set Target = Workbooks("Workbook2").Worksheets(1).Range(Cells(1, 1), Cells(4, 10))
Target.Value = Source.Value
End Sub