背景:
我在同一目录中有两个工作簿,每个工作簿中都有不同的工作表。
我想打开book2.xlsx,执行VBA,以复制book1.xls中“ sheet1”的全部内容。此后,book1.xls应该自动关闭。
我有一个代码,它将内容移动到工作表旁边,然后我必须将此工作表重命名为所需的工作表。问题是一个是我在另一张纸上的公式无法按预期工作。代码如下,
Sub XLVBACopyFiles()
Dim MonthlyWB As Variant
Dim FileName As String
FileName = ActiveWorkbook.Name
Path = ActiveWorkbook.Path & "\"
Application.DisplayAlerts = False
Application.EnableEvents = False
'Copy the sheet1 next to sheet2 in the current workbook
Application.Workbooks.Open (Path & "book1.xls")
Sheets(Array("sheet1")).Select
Sheets("sheet1").Activate
Sheets(Array("sheet1")).Move After:=Workbooks( _
FileName).Sheets("sheet2")
Application.EnableEvents = True
Application.DisplayAlerts = True
Workbooks(FileName).Save
' Workbooks(FileName).Close
End Sub
对此将提供任何帮助。
答案 0 :(得分:0)
如果您希望根据上面的评论将内容粘贴到“ sheet2本身”,请更新上面的代码:
Application.Workbooks.Open (Path & "book1.xls")
Sheets(Array("sheet1")).Select
Sheets("sheet1").Activate
**Sheets(Array("sheet1")).Move After:=Workbooks( _
FileName).Sheets("sheet2")**
到
Application.Workbooks.Open (Path & "book1.xls")
Sheets(Array("sheet1")).Select
Sheets("sheet1").Activate
'Next 2 lines will select the range of content to be copied, and CTRL+C it. Edit it to your desire range
Range("A1:A5").Select
Selection.Copy
Sheets("Sheet2").Select
Range("A1").Select ' In this line you should choose which cell to start pasting
ActiveSheet.Paste
此外,要关闭工作簿,请使用:
Workbooks("book1.xls").Close SaveChanges:=True
请注意SaveChanges选项,如果要保存或不保存此工作簿,请选择True / False