简体   繁体   中英

Export Range to New Excel Document VBA

I am new to VBA but working on some reports and it would be a lot simpler to create a macro button to auto export a defined range to a new .xlsx document.

I have so far:

Sub ExportTest()
    Dim WS As Worksheet
    Dim Rng As Range
    Set Rng = Range("A1:K10")
    Application.Workbooks.Add
    Set WS = Application.ActiveSheet
    Rng.Copy Destination:=WS.Range("A1")
    WS.SaveAs "test", ".xlsx"
End Sub

I get error 1004, which seems to be an issue with the SaveAs part.

But cannot figure out how to auto save this to a pre-defined folder. Also if possible would it be possible to reference the filename as a cell in the original workbook?

You have an error in the SaveAs syntax. Try this

WS.SaveAs "test", xlOpenXMLWorkbook

I think I solved it now thank you!

Sub Test()
Dim WS As Worksheet
Dim Rng As Range
Set Rng = Range("A1:K10")
Application.Workbooks.Add
Set WS = Application.ActiveSheet
Rng.Copy Destination:=WS.Range("A1")
Dim Path As String
Dim filename As String
Path = "C:\test\"
filename = Range("A1")
WS.SaveAs filename:=Path & filename & ".xlsx", FileFormat:=xlOpenXMLWorkbook
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM