从工作簿中获取1个工作表并将其另存为新的Excel文档

时间:2015-01-03 01:00:49

标签: vba excel-vba save excel

我有一个工作簿,保存为xyz.xlsm。此工作簿有3个工作表(sheet1,sheet2,sheet3)。我想在VBA中创建一个宏,它将复制sheet3并将其保存在路径G:\ Michael \ work \ uploadfiles中的新Excel文档中。我希望宏将此新文档命名为sheet2中单元格D3中的当前日期+文本内容,即。 (01/02/15 Mike Jones)。

2 个答案:

答案 0 :(得分:0)

我还没有测试过,但是这样的事情应该可行。

将当前图书定义为变量:

Set thisBook = ActiveWorkbook

然后您需要创建新的Excel文件:

Set newBook = Workbooks.Add

然后将sheet3从thisBook复制到newBook

thisBook.Sheets("sheet3").Copy After:=newBook.Sheets("Sheet1")

要保存新的,请执行以下操作:

dim filePath, thisDate as string
' VBA probably won't like the slashes in the date, so replace them.
thisDate = Replace(Date(),"\"," - ")
filePath = "G:\Michael\work\uploadfiles\" & thisDate & "Mike Jones.xlsx"
newBook.SaveAs FileName:= filePath

答案 1 :(得分:0)

以下代码完成了这项工作。

默认情况下,save1sheet会保存您在包含宏的工作簿中指明的工作表,但您可以选择活动工作簿(如果不同)或任何打开的工作簿。

Public Sub save1sheet(sheetNameOrNumber, toFile As String, Optional fromBook = "")
    Dim theBook As Workbook, theSheet As Worksheet
    If fromBook = "" Then
        Set theBook = ThisWorkbook
    ElseIf fromBook = "_active_" Then
        Set theBook = ActiveWorkbook
    Else
        Set theBook = Workbooks(fromBook)
    End If

    Set theSheet = theBook.Sheets(sheetNameOrNumber)
    theSheet.Copy
    ActiveWorkbook.Close True, toFile
End Sub

Sub saveTheSheets()
    Dim pathTemplate As String, path As String
    pathTemplate = "C:\Temp\{date} {person}.xlsx"
    ' G:\Michael\work\uploadfiles

    path = Replace(pathTemplate, "{date}", Replace(Date, "/", " - "))
    path = Replace(path, "{person}", "Mike Jones")
    save1sheet "sheet3", path

    path = Replace(pathTemplate, "{date}", Replace(Date, "/", " - "))
    path = Replace(path, "{person}", "Dirk Horsten")
    save1sheet 2, path, fromBook:="_active_"

    path = Replace(pathTemplate, "{date}", Replace(Date, "/", " - "))
    path = Replace(path, "{person}", "Hamilton Blake")
    save1sheet "Sheet1", path, fromBook:="ThatOtherBook.xlsx"
End Sub