msoFileDialogSaveAs set default file name in dialogue window - excel

I'm using the following VBA code to let the user choose a path to save a xlsm excel file as a xlsx file. The functionality is triggered by clicking a button in the xlsm excel file.
When I try it out, the name of the file in the saveas-window is empty, how can I set a default name (e.g. report_xyz) so the user does not have to type it himself?
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogSaveAs).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
strPath = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
'displays the result in a message box
Call MsgBox(strPath, vbInformation, "File got saved as")
End If
' Set to a xlsx file from xlsm
Application.DisplayAlerts = False 'switching off the alert button
Worksheets("Import_Sheet").Delete 'Delete Import Sheet
ActiveWorkbook.SaveAs strPath, FileFormat:=FileFormatNum ' save with new name and format

Preset the "save as type" field while using Application.FileDialog(msoFileDialogSaveAs) with MSAccess
i think
Application.FileDialog(msoFileDialogSaveAs).InitialFileName = "test"
before
intChoice = Application.FileDialog(msoFileDialogSaveAs).Show
will do the job

Related

Save as vba automatic pop up [duplicate]

I found code online that opens a Save As dialog to a location on a drive.
When you click "save" the file does not save.
Dim varResult As Variant
'displays the save file dialog
varResult = Application.GetSaveAsFilename(FileFilter:= _
"Excel Files (*.xlsx), *.xlsx", Title:="Save PO", _
InitialFileName:="\\showdog\service\Service_job_PO\")
'checks to make sure the user hasn't canceled the dialog
If varResult <> False Then
Exit Sub
End If
You have to actually explicitly tell Excel to save the workbook.
Sub Mac2()
Dim varResult As Variant
Dim ActBook As Workbook
'displays the save file dialog
varResult = Application.GetSaveAsFilename(FileFilter:= _
"Excel Files (*.xlsx), *.xlsx", Title:="Save PO", _
InitialFileName:="\\showdog\service\Service_job_PO\")
'checks to make sure the user hasn't canceled the dialog
If varResult <> False Then
ActiveWorkbook.SaveAs Filename:=varResult, _
FileFormat:=xlWorkbookNormal
Exit Sub
End If
End Sub
Using the GetSaveAsFilename only gets the path of the file to save, whereas the SaveAs method actually saves the workbook.
Upon some consideration, I might suggest using the SaveCopyAs method instead of simply SaveAs. As the name suggests, this will leave your original workbook in tact and save off a copy. To do this is a rather simply modification.
You would replace
ActiveWorkbook.SaveAs Filename:=varResult, _
FileFormat:=xlWorkbookNormal
With
ActiveWorkbook.SaveCopyAs Filename:=varResult
One final consideration I would add is that if you save your macro-enabled workbook as a .xlsx (either by SaveAs or the SaveCopyAs) then you will lose the macros, either in your original workbook if you use SaveAs or in the copy that is saved if you use SaveCopyAs. I would consider saving the file as a .xlsm instead, if you need macros to be available.
I prefer to use the shortest code:
Application.Dialogs(xlDialogSaveAs).Show ("c:\my_folder\")
It's the standard Excel save dialog.
It has several parameters (not named), you may need them:
Dim strFilename As String: strFilename = "report1"
Dim strFolder As String: strFolder = "C:\temp\" 'initial directory - NOTE: Only works if file has not yet been saved!
Dim xlfFileFormat As XlFileFormat: xlfFileFormat = XlFileFormat.xlOpenXMLWorkbook 'or replace by other XlFileFormat
Dim strPassword As String: 'strPassword = "password" 'The password with which to protect the file - if any
Dim booBackup As Boolean: 'booBackup = True '(Whether to create a backup of the file.)
Dim strWriteReservationPassword As String: 'strWriteReservationPassword = "password2" ' (The write-reservation password of the file.)
Dim booReadOnlyRecommendation As Boolean: booReadOnlyRecommendation = False '(Whether to recommend to the user that the file be opened in read-only mode.)
Dim booWorkbookSaved As Boolean ' true if file saved, false if dialog canceled
If Len(strFolder) > 0 Then ChDir strFolder
booWorkbookSaved = Application.Dialogs(xlDialogSaveAs).Show(Arg1:=strFilename, Arg2:=xlfFileFormat, Arg3:=strPassword, _
Arg4:=booBackup, Arg5:=strWriteReservationPassword, Arg6:=booReadOnlyRecommendation)

How do I import Excel data using dynamic path created/Input on Access Form

In MS Access, I created a form with Form Name "Form" and created a Text Box named "Path".
When I enter a path in form with "c:Desktop.....xlsx". I should be able to import data from Excel to Access.
I tried using the Macro version in Access using the below code, but I encounter an error.
Function Import()
On Error GoTo Import_Err
Dim Str As String
Str = Forms!Form!Path.Caption
DoCmd.TransferSpreadsheet acImport, 10, "EM", Str, True, ""
Import_Exit:
Exit Function
Import_Err:
MsgBox Error$
Resume Import_Exit
End Function
Error: "Object doesn't support this property or method".
As I plan to give the file to others to run, they will have a different path, so we need to prefix it in their system. So instead if we have form path, then users can input the path in form and run it.
Use this:
Str = Forms!Form.Path
I would (in your shoes) use the File Open Dialog instead letting users type the file with path:
Set FD = Application.FileDialog(msoFileDialogOpen)
Dim FileChosen As Integer
FileChosen = FD.show
FD.Title = "Choose workbook"
FD.InitialView = msoFileDialogViewList
FD.Filters.Clear
FD.Filters.add "Excel workbooks", "*.xlsx"
FD.Filters.add "All files", "*.*"
FD.FilterIndex = 1
FD.ButtonName = "Choose this file"
If FileChosen <> -1 Then
'didn't choose anything (clicked on CANCEL)
MsgBox "No file opened", vbCritical
GoTo Exit_Function
Else
fileNamePath = FD.SelectedItems(1)
End If
Set FD = Nothing
and after that
DoCmd.TransferSpreadsheet acImport, 10, "EM", fileNamePath , True
The Access Textbox control doesn't have a Caption property. But it does have two other properties:
Text property
Value property.
AFAICT, Text returns the text currently in the textbox, while Value returns the last persisted value. If the user has modified the text in the textbox but the focus is still in the texbox, Text will return the user-entered new value, but Value will return the value before the user started editing.
Note that you can only get and set Text when the control has the focus.

Saving to PDF adding blank page

I'm trying to create a macro that will allow my end users to click on one macro that will ask them for a PDF file that they would like to add as a new page. The page is based off a template and have a merged cell in the center for the image. I'm able to get the new page created as well as get a file explorer window with specific filters opened, but I have a couple questions for this.
Is it possible to get the full filepath from the file explorer to be put into a variable to later use during the PDF insertion(as my end users may have PDF's saved in different directories)?
Code for the question:
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters
.Filters.Clear
.Filters.Add "PDF Files", "*.PDF"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'txtFileName will return the file
End If
End With
Is it possible to insert a PDF image into an excel cell and have it fit the cells dimensions?
Code for the question:
tempRow = lastRow + 9
'Sets the correct row/column
Set rng = crrntWorkbook.Sheets(1).Range("B" & tempRow)
'This portion is trying to insert the PDF as an OLEObject picture
crrntWorkbook.Sheets(1).Range("B" & tempRow) = crrntWorkbook.Sheets(1).OLEObjects.Add(Filename:=txtFileName,_
DisplayAsIcon:=False).activate
Any help with these issues would be greatly appreciated!

How can I open multiple Excel files and execute a contained macro on each?

I'm looking to open multiple Excel files and run the same macro (contained in each) on each file.
For example, I'd like to automatically open every file in h:\dbs and execute the CmdUpdate_Click macro within each file.
How might I go about this?
Try something like this. I expect you can research how to open the Visual Basic Editor and figure out where to paste this.
'Declare variables
Dim FolderObj, FSO, FileObj As Object
Dim FolderDialog As FileDialog
'Create and run dialog box object
Set FolderDialog = Application.FileDialog(msoFileDialogFolderPicker)
With FolderDialog
.ButtonName = "Select"
.AllowMultiSelect = False
.InitialFileName = "B:\BIM Projects\"
.InitialView = msoFileDialogViewDetails
'Check if user canceled dialog box
'Exit if yes
If .Show = -1 Then
MsgBox "No Folder Selected"
Exit Sub
End If
End With
'Check if user canceled dialog box
'Exit if yes
'Create a File System Object to be the folder that was selected
Set FSO = CreateObject("scripting.filesystemobject")
Set FolderObj = FSO.getfolder(FolderLocation)
'For each obj in the selected folder
For Each FileObj In FolderObj.Files
'Test if the file extension contains "xl" and make sure it's an Excel file before opening
If InStr(1, Right(FileObj.Name, Len(FileObj.Name) - InStr(1, FileObj.Name, ".")), "xl") = 1 Then
'Prevent the workbook from displaying
ActiveWindow.Visible = False
'Open the Workbook
Workbooks.Open (FolderObj & "\" & FileObj.Name)
'Run the Macro
Application.Run "'" & FolderObj & "\" & FileObj.Name & "'!CmdUpdate_Click"
'Save the Workbook
Workbooks(FileObj.Name).Save
'Close the Workbook
Workbooks(FileObj.Name.Close
End If
'Turn this back on
ActiveWindow.Visible = True
Next
I will caution you that this is based on some code I wrote for Word, so there are no guarantees it will work and I don't have time to test it. It will, however, give you a very good start if it doesn't.
Edit to Add: You may

How to save a file selected in Save As dialog?

I found code online that opens a Save As dialog to a location on a drive.
When you click "save" the file does not save.
Dim varResult As Variant
'displays the save file dialog
varResult = Application.GetSaveAsFilename(FileFilter:= _
"Excel Files (*.xlsx), *.xlsx", Title:="Save PO", _
InitialFileName:="\\showdog\service\Service_job_PO\")
'checks to make sure the user hasn't canceled the dialog
If varResult <> False Then
Exit Sub
End If
You have to actually explicitly tell Excel to save the workbook.
Sub Mac2()
Dim varResult As Variant
Dim ActBook As Workbook
'displays the save file dialog
varResult = Application.GetSaveAsFilename(FileFilter:= _
"Excel Files (*.xlsx), *.xlsx", Title:="Save PO", _
InitialFileName:="\\showdog\service\Service_job_PO\")
'checks to make sure the user hasn't canceled the dialog
If varResult <> False Then
ActiveWorkbook.SaveAs Filename:=varResult, _
FileFormat:=xlWorkbookNormal
Exit Sub
End If
End Sub
Using the GetSaveAsFilename only gets the path of the file to save, whereas the SaveAs method actually saves the workbook.
Upon some consideration, I might suggest using the SaveCopyAs method instead of simply SaveAs. As the name suggests, this will leave your original workbook in tact and save off a copy. To do this is a rather simply modification.
You would replace
ActiveWorkbook.SaveAs Filename:=varResult, _
FileFormat:=xlWorkbookNormal
With
ActiveWorkbook.SaveCopyAs Filename:=varResult
One final consideration I would add is that if you save your macro-enabled workbook as a .xlsx (either by SaveAs or the SaveCopyAs) then you will lose the macros, either in your original workbook if you use SaveAs or in the copy that is saved if you use SaveCopyAs. I would consider saving the file as a .xlsm instead, if you need macros to be available.
I prefer to use the shortest code:
Application.Dialogs(xlDialogSaveAs).Show ("c:\my_folder\")
It's the standard Excel save dialog.
It has several parameters (not named), you may need them:
Dim strFilename As String: strFilename = "report1"
Dim strFolder As String: strFolder = "C:\temp\" 'initial directory - NOTE: Only works if file has not yet been saved!
Dim xlfFileFormat As XlFileFormat: xlfFileFormat = XlFileFormat.xlOpenXMLWorkbook 'or replace by other XlFileFormat
Dim strPassword As String: 'strPassword = "password" 'The password with which to protect the file - if any
Dim booBackup As Boolean: 'booBackup = True '(Whether to create a backup of the file.)
Dim strWriteReservationPassword As String: 'strWriteReservationPassword = "password2" ' (The write-reservation password of the file.)
Dim booReadOnlyRecommendation As Boolean: booReadOnlyRecommendation = False '(Whether to recommend to the user that the file be opened in read-only mode.)
Dim booWorkbookSaved As Boolean ' true if file saved, false if dialog canceled
If Len(strFolder) > 0 Then ChDir strFolder
booWorkbookSaved = Application.Dialogs(xlDialogSaveAs).Show(Arg1:=strFilename, Arg2:=xlfFileFormat, Arg3:=strPassword, _
Arg4:=booBackup, Arg5:=strWriteReservationPassword, Arg6:=booReadOnlyRecommendation)

Resources