'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
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CDP1802 |
| Solution 2 | VBasic2008 |
