简体   繁体   中英

Sheet To Workbook using VBA

I have found the below code to save sheet as new workbook but what I wanted to know if it is possible to change the save name each time the macro is run to the value on sheet 1 in cells B2 and to a specific file location.

I have tried the way below and it just simply saves the file with the name of the file location instead of saving it in the file location specified.

Sub sb_Copy_Save_Worksheet_As_Workbook() 
    Dim wb As Workbook 
    Set wb = Workbooks.Add 
    ThisWorkbook.Sheets("Sheet2").Copy Before:=wb.Sheets(1) 
    wb.SaveAs "C:\temp\test1.xlsx" 
End Sub

Any help would be greatly appreciated

many thanks

Jamie

Let's say "Sheet1" has in cell B2 the value "test1" (the filename), then you can use the following:

Sub sb_Copy_Save_Worksheet_As_Workbook()
    Dim wb As Workbook
    Dim myPath As String
    Dim myFilename As String
    Dim myFileExtension As String
    myPath = "C:\temp\" 'you can change this
    myFileExtension = ".xlsx"
    myFilename = ThisWorkbook.Sheets("Sheet1").Range("B2").Value
    Set wb = Workbooks.Add
    ThisWorkbook.Sheets("Sheet2").Copy Before:=wb.Sheets(1)
    wb.SaveAs myPath & myFilename & myFileExtension
    wb.Close False
End Sub

If your cell B2 already includes the file extension (so it is "test1.xlsx" in B2), just remove the myFileExtension parts from the code.

The folder, where you want to save your file has to exist. If you need help checking this or creating the folder in your macro, please leave a comment.

Try adding on the cell value to the path string like this:

Sub sb_Copy_Save_Worksheet_As_Workbook()
    Dim wb As Workbook
    Set wb = Workbooks.Add
    ThisWorkbook.Sheets("Sheet2").Copy Before:=wb.Sheets(1)
    wb.SaveAs "C:\temp\" & ThisWorkbook.Sheets("Sheet2").Range("B2").Value
End Sub

File extension will default to .xlsx even if the original file is .xlsm so you don't need to add this to the path string.

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