VBA将范围另存为工作簿

时间:2018-07-26 14:08:30

标签: excel vba excel-vba

我正在尝试将范围另存为单独的工作簿。我要保存的范围是工作表(STF)和范围(从B1到J lastrow),我的代码是:

saveFile = Application.GetSaveAsFilename(InitialFileName:=address & " " & Format(Now(), "yyyy-MM-dd hh-mm-ss"), fileFilter:="Excel Workbooks (*.xlsx),*.xlsx")
Worksheets("STF").Range("B1:J" & LR).SaveAs Filename:=saveFile

但是,显然不是那么简单。它失败了,我不确定如何解决此问题?

帮助?

2 个答案:

答案 0 :(得分:2)

将工作表复制到任何位置。这将创建一个包含工作表的新工作簿(新活动)。

Option Explicit

Sub extractRange()
    Dim saveFile As String, Address As String

    Address = "ABC"

    saveFile = Application.GetSaveAsFilename(InitialFileName:=Address & " " & Format(Now, "yyyy-MM-dd hh-mm-ss"), _
                                             fileFilter:="Excel Workbooks (*.xlsx),*.xlsx")
    ThisWorkbook.Worksheets("STF").Copy

    With ActiveWorkbook
        With .Worksheets("STF")
            .Columns("K:XFD").EntireColumn.Delete
            .Columns("A").EntireColumn.Delete
        End With
        .SaveAs Filename:=saveFile, FileFormat:=xlOpenXMLWorkbook
        .Close savechanges:=False
    End With
End Sub

答案 1 :(得分:1)

创建工作簿,将所需范围复制/粘贴到新工作簿,然后保存并关闭:

saveFile = Application.GetSaveAsFilename(InitialFileName:=Address & " " & Format(Now(), "yyyy-MM-dd hh-mm-ss"), fileFilter:="Excel Workbooks (*.xlsx),*.xlsx")
If Not saveFile = "False" Then
    With Workbooks.Add
        ThisWorkbook.Worksheets("STF").Range("B1:J" & LR).Copy .Sheets(1).Range("B1")
        .SaveAs saveFile
        .Close
    End With
End If