从打开的工作簿中的单个工作表中创建新的Excel工作簿

时间:2019-02-25 21:30:30

标签: excel file save export creation

我正在尝试从打开的表中创建一个新的Excel文件。我在这里经历过几种解决方案,但是没有一个能够完全满足我的需求。我对磁盘上的Excel文件交互不是很好。这是Excel 2010。

  1. 我有一些VBA代码,可将相关数据写到新工作表中(例如Sheet3)。
  2. 然后,我想将Sheet3的所有内容写到给定文件夹中的新Excel文件“ output.xlsx”中(假设F:\ test)
  3. 我希望该过程可以盲目创建xlsx文件,填充Sheet1,保存并关闭文件,而用户却看不到打开的output.xlsx文件。

编辑#2:使用此确切的代码:

Dim FPath As String, FName As String, filenamex As String
Dim NewBook As Workbook

Application.DisplayAlerts = False
Application.ScreenUpdating = False

FPath = "F:\test\"
FName = "output" & ".xlsx"
filenamex = FPath & FName
Set NewBook = Workbooks.Add
Worksheets("Sheet3").Range("A1:N100").Copy 
Destination:=NewBook.Worksheets("Sheet1").Range("A1")
Application.CutCopyMode = False
NewBook.Close savechanges:=True, Filename:=filenamex

Application.DisplayAlerts = True
Application.ScreenUpdating = True

结果2: (a)创建并保存了excel文件output.xls(谢谢) (b)创建三张原始文件中存在的文件 (c)所有三张纸仍为空白。我只需要从原始文件中复制Sheet3。

谢谢

1 个答案:

答案 0 :(得分:0)

主要,您可以仅关闭ScreenUpdating

Sub copy_to_new()
Application.DisplayAlerts = False
Application.ScreenUpdating = False

Dim FPath As String, FName As String, filenamex As String
Dim NewBook As Workbook, oldBook as Workbook

Set oldBook = ActiveWorkbook 
'Or use `ThisWorkbook` if you're running this code from the workbook you want to copy from.

FPath = "F:\test\"
FName = "output.xls"
filenamex = FPath & FName
Set NewBook = Workbooks.Add
oldBook.Worksheets("Sheet3").Range("A1:N100").Copy Destination:=NewBook.Worksheets("Sheet1").Range("A1")
Application.CutCopyMode = False

' We can use the .Close command to close and save the file in one line
NewBook.Close savechanges:=True, Filename:=filenamex

Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub