I'm trying to get my Save As path to open up as the same folder the original document was opened from. For example, if the file was in public/forms I want it prompt save as in public/forms. Currently it is defaulting to mypc/documents. This is my code:
Dim IntialName As String
Dim fileSaveName As Variant
InitialName = Range("d1") & "_" & "#" & Range("l1") & "-" & "RW" &
Range("q1")
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
filefilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
If fileSaveName = False Then
Exit Sub
End If
If Not fileSaveName = False Then
ActiveWorkbook.SaveAs Filename:=Application.ThisWorkbook.Path &
fileSaveName
Else
On Error Resume Next
If Err.Number = 1004 Then
On Error GoTo 0
Else
ActiveWorkbook.SaveAs Filename:=Application.ThisWorkbook.Path &
fileSaveName
End If
End If
Thanks!
The code below will save to the file name you've used. I've made it reference the ranges on Sheet1 rather than whichever sheet is currently active when your execute the code. Change the sheet name as required.
It will also open to the folder that the file containing the code is in (ThisWorkbook).
Change this to ActiveWorkbook or any other path as required.
Sub Test1()
Dim InitialName As String
With ThisWorkbook.Worksheets("Sheet1")
InitialName = .Range("D1") & "_" & "#" & .Range("L1") & "-" & "RW" & .Range("Q1")
InitialName = ThisWorkbook.Path & "\" & InitialName
End With
InitialName = Application.GetSaveAsFilename(InitialName, "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
If Not InitialName = "False" Then
ThisWorkbook.SaveAs InitialName
End If
End Sub
Assuming that InitialName contains only a filename without path, change the parameter InitialFileName to
Application.GetSaveAsFilename(InitialFileName:= thisWorkbook.Path & "\" & InitialName, ...
I think this is what you want:
File filter can take a full folder in the initial path, so you can assign it based on the workbooks path
Dim InitialName As String
Dim fileSaveName As Variant
Dim FilePath, FileOnly, PathOnly As String
FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
InitialName = PathOnly & "\" & Range("d1") & "_" & "#" & Range("l1") & "-" & "RW" &
Range("q1")
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
filefilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
If fileSaveName = False Then
Exit Sub
End If
If Not fileSaveName = False Then
ActiveWorkbook.SaveAs Filename:=Application.ThisWorkbook.Path & fileSaveName
Else
On Error Resume Next
If Err.Number = 1004 Then
On Error GoTo 0
Else
ActiveWorkbook.SaveAs Filename:=Application.ThisWorkbook.Path & fileSaveName
End If
End If
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
filefilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
Related
I am a newbie in excel vba coding and trying to create pdf of a excel sheet range. My code works well in windows OS but somehow it doesn't work in Mac OS. The Code is as below:
`
Sub GeneratePDF()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim VelleName As String
Dim SelectedRange As Range
With ThisWorkbook.Worksheets("modulo")
.Activate
.Range(.Cells(1, 1), .Cells(33, 10)).Select
Selection.Name = "SelectedRange"
End With
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveWorkbook.Worksheets("modulo")
strTime = Format(Now(), "ddmmyyyy\_hhmm")
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
VelleName = ThisWorkbook.Worksheets("database").Range("B" & Desiredrow) & "_" & ThisWorkbook.Worksheets("database").Range("C" & Desiredrow)
'replace spaces and periods in sheet name
strName = Replace(VelleName, " ", "_")
strName = Replace(strName, ".", "_")
strName = Replace(strName, "-", "_")
strName = Replace(strName, "/", "_")
'create default name for savng file
strFile = strName & "_" & strTime & ".pdf"
strPathFile = strName & "_" & strTime
' select folder for file
If Dir(strPath & Application.PathSeparator & "forme", vbDirectory) = "" Then '<== check if folder exists but its not detecting even though i had created a folder there.
MkDir (ThisWorkbook.Path & Application.PathSeparator & "forme") '<== Create Folder and its not working for Mac OS.
End If
myFile = ThisWorkbook.Path & Application.PathSeparator & "forme" & Application.PathSeparator & strPathFile
'export to PDF if a folder was selected
If myFile <> "False" Then
With wsA.PageSetup
.Orientation = xlPortrait
.PrintArea = "SelectedRange"
.Zoom = False
.FitToPagesTall = 1
.FitToPagesWide = 1
End With
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "Il file pdf รจ stato creato: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Impossibile creare il file pdf"
Resume exitHandler
End Sub
`
I have tried searching a lot on internet but havent found any source which specifically teaches vba coding in Mac OS. Moreover, i got only one link https://macexcel.com/examples/filesandfolders/makefolder/ but i dont think it would work as it should be only one line of command and the biggest issue i dont have Mac OS available now. So can somebody test my code change my command to make it compatible it with Mac OS
I used to use this code and also add to check file exist
'Only Change code Here
Sub Verify()
Dim myPath As String
myPath = "C:\abc" '<--------This line
If Not PathExist(myPath) Then MkDir (myPath)
End Sub
Private Function PathExist(path_ As String) As Boolean
On Error GoTo ErrNotExist
Call ChDir(path_)
PathExist = True
Exit Function
ErrNotExist:
PathExist = False
End Function
Private Function FileExist(filePath_ As String) As Boolean
FileExist = Len(Dir(filePath_)) <> 0
End Function
i need a modification in this code to suppress save as dialogbox(save file as pdf in mentioned location (C:\Users\hazem\Desktop\New folder (4)\HM\PDF) without any save as screen appears and without excel workbook name changed)_
note :_
i work on windows 10 ,excel ver. 2019
this code is part of macro
(Application.DisplayAlerts = False _
""code between""_
Application.DisplayAlerts = true)
doesn't work with me
This is the code:
Sub PDFActiveSheet()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim MyFile As Variant
Dim answer As Integer
Dim fnd As Variant
Dim rplc As Variant
Filename1 = Range("B4")
filename2 = Range("G11")
filename3 = Range("M4")
filename4 = Range("B4")
filename5 = Range("B5")
filename6 = Range("C5")
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strTime = Format(Now(), "yyyy-mm-dd_hhmm")
strPath = "C:\Users\hazem\Desktop\New folder (4)\HM\PDF"
If strPath <> "C:\Users\hazem\Desktop\New folder (4)\HM\PDF" Then
Exit Sub
End If
strPath = strPath & "\"
'replace spaces and periods in sheet name
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
'create default name for savng file
strFile = Filename1 & "_" & filename3 & " " & "of" & " " & filename2 & " " & "at" & " " & strTime & ".pdf"
strPathFile = strFile
'use can enter name and
' select folder for file
answer = MsgBox("Please!! Save the PDF to path (FINISHED CRS PDF OF SELECTED AUTHORITY) ", vbQuestion + vbYesNo + vbDefaultButton2, "CRS PDF CREATOR")
If answer = vbNo Then MsgBox "Please! Try again Later"
If answer = vbNo Then Exit Sub
Application.DisplayAlerts = False
ActiveWorkbook.Close savechanges:=True
MyFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
Application.DisplayAlerts = False
If MyFile = Cancel Then Exit Sub
'export to PDF if a folder was selected
MsgBox "PDF file wil be opened in seconds "
MsgBox "please click CTRL+P to print PDF and change copies to the no. you need"
If MyFile <> "False" Then
Application.EnableEvents = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=MyFile, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Application.EnableEvents = True
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& MyFile
MsgBox "Your Work is done here!"
MsgBox "Thank you"
End If
End sub
I have an excel workbook with multiple sheets, i'm trying to export a particular sheet as a CSV file and save it to the users desktop without impacting the original. Everything seems to work, however the file is coming out as a PDF, any ideas? Code is below:
Sub CSVSagePricelist_Click()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim TempWB As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = Sheet8
strTime = Format(Now(), "yyyymmdd\_hhmm")
'get active workbook folder, if saved
strPath = CreateObject("WScript.Shell").specialfolders("Desktop")
If strPath = "" Then
strPath = CreateObject("WScript.Shell").specialfolders("Desktop")
End If
strPath = strPath & "\"
'replace spaces and periods in sheet name
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
'create default name for saving file
strFile = "INT-ONLY-SAGE-PRICELIST" & "_" & Sheet16.Range("C17").Text & "_" & Sheet16.Range("B2").Text & ".csv"
strPathFile = strPath & strFile
'use can enter name and
'select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="CSV (Comma delimited) (*.csv), *.csv", _
Title:="Select Folder and FileName to save")
'export to PDF if a folder was selected
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlCSV, _
Filename:=myFile
'confirmation message with file info
MsgBox "Sage pricebook CSV created: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create CSV file"
Resume exitHandler
End Sub
Thanks,
Nick
Following code lines / code blocks are needed to corrected. Also you should include Option Explicit in the beginning of code so that undeclared variables are easily identified.
A.)
Set wsA = Sheet8
Will give Compiler error. Variable not defined. It should be changed to
Set wsA = Sheets("Sheet8")
Similarly
strFile = "INT-ONLY-SAGE-PRICELIST" & "_" & Sheet16.Range("C17").Text & "_" & Sheet16.Range("B2").Text & ".csv"
strPathFile = strPath & strFile
It should be changed to
strFile = "INT-ONLY-SAGE-PRICELIST" & "_" & Sheets("Sheet16").Range("C17").Text & "_" & Sheets("Sheet16").Range("B2").Text & ".csv"
strPathFile = strPath & strFile
B.) Block of code for saving as pdf file has incorrect syntax.
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlCSV, _
Filename:=myFile
'confirmation message with file info
MsgBox "Sage pricebook CSV created: " _
& vbCrLf _
& myFile
End If
Needs to be Changed to
'export to PDF if a folder was selected
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
End If
With these changes your final code should work fine.
Option Explicit
Sub CSVSagePricelist_Click()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim TempWB As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = Sheets("Sheet8")
strTime = Format(Now(), "yyyymmdd\_hhmm")
'get active workbook folder, if saved
strPath = CreateObject("WScript.Shell").specialfolders("Desktop")
If strPath = "" Then
strPath = CreateObject("WScript.Shell").specialfolders("Desktop")
End If
strPath = strPath & "\"
'replace spaces and periods in sheet name
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
'create default name for saving file
strFile = "INT-ONLY-SAGE-PRICELIST" & "_" & Sheets("Sheet16").Range("C17").Text & "_" & Sheets("Sheet16").Range("B2").Text & ".csv"
strPathFile = strPath & strFile
'use can enter name and
'select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="CSV (Comma delimited) (*.csv), *.csv", _
Title:="Select Folder and FileName to save")
'export to PDF if a folder was selected
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create CSV file"
Resume exitHandler
End Sub
I am getting a Runtime error 1004 document not saved using vba when I want to save an Excel workbook in my folder on desktop. Here are the details of my code:
Private Sub Save_Click()
'Popup the Window "Save As"
Application.DisplayAlerts = False
MsgBox "Do not change the default file name proposed on the next step please !"
Dim fName As Variant
Dim DName As String ' Variable storing name of excel workbook which has to be saved
DName = UserForm.CustomerApplication.Value & " - " & UserForm.L2GType.Value
& " - " & UserForm.Title.Value & " - " & UserForm.Country.Value & "(" &
Year(Date) & ")"
fName = Application.GetSaveAsFilename(InitialFileName:=DName, _
FileFilter:="Excel Files (*.XLSX), *.XLSX", Title:="Save As")
If fName = False Then
Exit Sub
ActiveWorkbook.SaveAs filename:=fName, FileFormat:=51
ActiveWorkbook.Close
End Sub
I think you are missing an 'End If' at the bottom of your code. The 'If fName = False Then...' part. Try the following
Private Sub Save_Click()
'Popup the Window "Save As"
Application.DisplayAlerts = False
MsgBox "Do not change the default file name proposed on the next step please !"
Dim fName As Variant
Dim DName As String ' Variable storing name of excel workbook which has to be saved
DName = UserForm.CustomerApplication.Value & " - " & UserForm.L2GType.Value
& " - " & UserForm.Title.Value & " - " & UserForm.Country.Value & "(" &
Year(Date) & ")"
fName = Application.GetSaveAsFilename(InitialFileName:=DName, _
FileFilter:="Excel Files (*.XLSX), *.XLSX", Title:="Save As")
If fName = False Then
Exit Sub
End If
ActiveWorkbook.SaveAs filename:=fName, FileFormat:=51
ActiveWorkbook.Close
End Sub
fName is a String, therefore you can't compare it with False, but with "False".
Try replacing the last section of your code with the lines below:
fName = Application.GetSaveAsFilename(InitialFileName:=DName, _
fileFilter:="Excel Files (*.XLSX), *.XLSX", Title:="Save As")
If fName <> "False" Then
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=fName, FileFormat:=51
Else
MsgBox "No File was selected !"
Exit Sub
End If
Application.DisplayAlerts = True
Note: using FileFormat:=51, means xlOpenXMLWorkbook, an .xlsx format (without MACROs).
However since you want to use the SaveAs command with ThisWorkbook, which contains this code, you will get a prompt screen that asks if you want to save it as .xslx , which means all your code will be lost.
You can select FileFormat:=52, means xlOpenXMLWorkbookMacroEnabled, an .xlsm format (with MACROs).
By clicking a button in Excel, the user exports a specific sheet to a csv with a dynamic filename and the csv is saved in a pre-determined directory.
Instead of saving to a predetermined directory, can users have the browse window to choose a directory to save to?
Sub Export()
Dim MyPath As String
Dim MyFileName As String
MyPath = "C:\importtest"
MyFileName = "MR_Update_" & Sheets("Monthly Review").Range("D3").Value & "_" & Format(Date, "ddmmyyyy")
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("Export Data").Copy
With ActiveWorkbook
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False
.Close False
End With
End Sub
Excel has an inbuilt FileSave Dialog. It is called .GetSaveAsFilename. Use that.
Syntax
expression.GetSaveAsFilename(InitialFilename, FileFilter, FilterIndex, Title, ButtonText)
Usage
Dim fileSaveName As Variant
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Excel Files (*.csv), *.csv")
If fileSaveName <> False Then
'
'~~> Your code to save the file here
'
End If
As Patrick suggested, you're looking for the .FileDialog property.
To implement it, try this:
Sub Export()
Dim MyPath As String
Dim MyFileName As String
MyFileName = "MR_Update_" & Sheets("Monthly Review").Range("D3").Value & "_" & Format(Date, "ddmmyyyy")
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("Export Data").Copy
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = "" '<~~ The start folder path for the file picker.
If .Show <> -1 Then GoTo NextCode
MyPath = .SelectedItems(1) & "\"
End With
NextCode:
With ActiveWorkbook
.SaveAs Filename:=MyPath & MyFileName, FileFormat:=xlCSV,CreateBackup:=False
.Close False
End With
End Sub
Try This......
Sub Export()
Dim MyPath As String
Dim MyFileName As String
MyPath = "C:\importtest"
MyFileName = "MR_Update_" & Sheets("Monthly Review").Range("D3").Value & "_" & Format(Date, "ddmmyyyy")
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("Export Data").Copy
With ActiveWorkbook
.SaveAs Filename:= _
MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False
.Close False
End With
End Sub
Here's a script I've been using lately that I like a lot. Thought I would leave this here:
Sub ExportCSV()
Dim FlSv As Variant
Dim MyFile As String
Dim sh As Worksheet
Dim MyFileName As String
Dim DateString As String
DateString = Format(Now(), "yyyy-mm-dd_hh_mm_ss_AM/PM") '<~~ uses current time from computer clock down to the second
MyFileName = DateString & "_" & "Whatever you like"
Set sh = Sheets("Sheet you'd like to export")
sh.Copy
FlSv = Application.GetSaveAsFilename(MyFileName, fileFilter:="CSV (Comma delimited) (*.csv), *.csv", Title:="Where should we save this?")
If FlSv = False Then GoTo UserCancel Else GoTo UserOK
UserCancel: '<~~ this code is run if the user cancels out the file save dialog
ActiveWorkbook.Close (False)
MsgBox "Export canceled"
Exit Sub
UserOK: '<~~ this code is run if user proceeds with saving the file (clicks the OK button)
MyFile = FlSv
With ActiveWorkbook
.SaveAs (MyFile), FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
End Sub