简体   繁体   中英

VBA to save worksheet to current folder

I'm currently using the following VBA to save a worksheet as a separate file, however it saves it to the My Documents folder instead of the current folder the workbook is in.

I'm looking help on what I could add so that it saves to the same folder as the file is already in. I can't hardcode a filepath in as it will change each month.

Sub SavePlan()
Dim Fname As String
Fname = Sheets("Main").Range("C6").Value
Sheets("Main").Copy
With ActiveWorkbook
    .SaveAs Filename:=Fname
    .Close
End With
End Sub

Thanks in advance

SaveAs is looking for the full path to save to, so use ActiveWorkbook.Path to get the directory the active workbook is in, then append \ and Fname to it (assuming you are working in Windows).

Sub SavePlan()

  Dim Fname As String
  Fname = Sheets("Main").Range("C6").Value
  
  Sheets("Main").Copy
  With ActiveWorkbook
    .SaveAs Filename := ActiveWorkbook.Path & "\" & Fname
    .Close
    End With

End Sub
Sub SavePlan() Dim Fname As String With Sheets("Main") Fname = .Parent.Path & "\" & .Range("C6").Value .Copy End With With ActiveWorkbook .SaveAs Filename:=Fname .Close End With End Sub

Backup Worksheet to a New Workbook

Option Explicit

Sub SavePlan()
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim sws As Worksheet: Set sws = wb.Worksheets("Main")
    
    Dim FolderPath As String: FolderPath = wb.Path
    Dim dFileName As String: dFileName = sws.Range("C6").Value
    Dim dFilePath As String
    dFilePath = FolderPath & Application.PathSeparator & dFileName
    
    sws.Copy ' copy to a new (destination) workbook
    
    Dim dwb As Workbook: Set dwb = Workbooks(Workbooks.Count)
    
    Application.DisplayAlerts = False ' overwrite without confirmation
    dwb.SaveAs Filename:=dFilePath
    Application.DisplayAlerts = True
    
    dwb.Close SaveChanges:=False

    MsgBox "Worksheet backed up.", vbInformation

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