Logicwurks Home Page

Links To Excel Code Examples

Tracing VBA Statements
Range/Wkb/Wks Variables
Add Grand Totals Using Ranges
Using Range Offset Property
Using Range Find Method
ConvertCellAddressToRange
Set Conditional Formatting
Union Of Ranges
Parse Range Strings
Delete Duplicate Rows
Delete Rows And Columns
Worksheet Variables
TypeName And TypeOf
Loop Through Worksheets
Loop Through Open Workbooks
Form Button Magic
Command Button Magic
Add Worksheets Dynamically
ImportExternalWorksheets
Find Last Row Or Column
Copy And Paste Special
Copy To Specific Cell Types
Range Copy With Filter
ExcelFileOpenSaveClose
ExcelFileOpenSaveCSV
Open An Excel File
Open An Excel File w/Params
Open An Excel File On Web
Save A Workbook
Save A Workbook Using mso
Clone A Workbook
Test If WEB URL Exists
Parse Using Split Command
Using Classes in Excel
TypeStatementStructures
Color Management
Convert Cell Color To RGB
Sort Methods 2003 - 2010
Sort Alpha/Numeric In ASCII
Search Using Match Function
Search Using Vlookup Function
Search Using Xlookup Function
Using Find Instead of Vlookup
Remove String Non-Printables
Auto_Open And Auto_Close
Initialize Form At Open
Edit Numerics In UserForm
Load Combo And List Boxes
Floating Sheet Combo Boxes
Advanced User Form Coding
Excel Events
Worksheet Change Events
Binary Search Of Array
Typecast Constants
Excel Error Handling
Handling Optional Parameters
Data Validation Drop Downs
Insert Data Validation Sub
Read A Text File w/Handle
Write A Text File w/Handle
Read a Binary File w/Handle
Update a Binary File w/Handle
Binary File Copy and Update
Read A Text Fiile w/Script
Text File Processing Examples
Test For Exists Or Open
Splash Screen
Dynamically Load Formulas
PaymentStreamsByDate
Date Examples
Date Find Same Days
Convert Month To Number
Initialize Arrays
Load Arrays Using Evaluate
ChartsAndGraphsVBA
Redim An Array
Reassign Button Action
Timer Functions
Legacy Calendar Control
Excel 2010 Date Picker
Date Picker Alternative
Generate Multiple Worksheets
Read Access Data Into Excel
Send Outlook Email w/Attach
Copy AutoFilters To Sheets
Export A Text File
Get Windows User Name
VBA Format Statement
Manipulate Files via VBA
Dynamically Load Images
Loop Through Worksheet Objects
Loop Through Form Objects
Loop Through Files with DIR
Active-X Checkboxes
Add Forms Checkboxes Dynam
Paste Pictures Into Excel
Copy Pictures Sheet To Sheet
Copy Pictures Sheet To Sheet
Create Forms Buttons With VBA
Extract Filename From Path
Convert R1C1 Format to A1
Special Cells Property
Insert Cell Comments

Links To Access Code Examples

DAO Versus ADODB
SearchVBACodeStrings
Interface Excel With Access
Create Form Manually
Create Recordset With AddNew
Multi-Select List Boxes
Update Field(s) In A Recordset
Update Excel Pivot From Access
Import A Tab Delimited File
Export Excel FileDialog
Create Excel Within Access
Open Excel Within Access
Open Excel OBJ From Access
Format Excel From Access
Control Excel via Access VBA
On Error Best Practices
Import Tab Delim w/WinAPI
Initialize Global Variables
Using TempVars For Globals
Access Error Handling
Loop Through Form Controls
Insert A Calendar Control
Create A Filtered Recordset
Populate Combo Boxes
Bookmarks And Forms
Combo Box Multiple Sources
Passing Form Objects
Create VBA SQL Statements
Create Dynamic Queries
Display File Images On A Form
Manipulate Files via VBA
Manipulate Files via Scripting
Number Subform Records
Reference Subform Objects
Parse Delimited Fields
Parameterized Queries (VBA)
Manipulating QueryDefs In VBA
FindFirst On Combined Keys
Dlookup Command
Dlookup In Form Datasheet
Execute SQL Delete Records
Commit Form To Table
Report With No Data
Reference Form Objects
DSNLess Connections To MySQL
Print Active Form Record
Count Records in Linked Tables
Delete Empty Tables
Open Linked SQL Tables

 

Save A Workbook Using The File Save Dialog Box

The following code will prompt the user for a target directory, and save a workbook with the name that the user enters into the dialog box. The example below saves the workbook as an xlsm file.

For all the possible formats in the Workbook.SaveAs FileFormat:=, see this article:

FileFormat:= Specifications

Program Code

Option Explicit
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Public Sub GetTemplatePath()
Dim strPathToJobInfoTemplate As String
Dim strJobInfoWorkbookToSave As Variant

Dim wkbJobInfoWorkbook As Workbook

' *************************************************************
' Construct The Path To The Job Info Template
' *************************************************************
strPathToJobInfoTemplate = "C:\Users\" & UserNameWindows() & "\Documents\JobInfoTemplate\JobInfoTemplate.xlsm"

' *************************************************************
' Open The Template
' *************************************************************
On Error GoTo NoTemplateFound
Workbooks.Open strPathToJobInfoTemplate
On Error GoTo 0

Set wkbJobInfoWorkbook = ActiveWorkbook

' *************************************************************
' Open A Dialog Box For The User To Save The File
' *************************************************************
strJobInfoWorkbookToSave = Application.GetSaveAsFilename("", _
                 "Excel Files (*.xlsm), *.xlsm", , "Save Job Info Sheet")

' *************************************************************
' Make Sure A Valid Name and Path Were Selected
' *************************************************************
If strJobInfoWorkbookToSave = False Then
    MsgBox ("You Did Not Select A File Name For Export" & vbCrLf & _
           "Please Start Over")
    Application.ScreenUpdating = True
    Exit Sub
End If

' *************************************************************
' Activate This Workbook
' *************************************************************
ThisWorkbook.Activate

' *************************************************************
' Save the Job Info Workbook
' *************************************************************
wkbJobInfoWorkbook.SaveAs Filename:=strJobInfoWorkbookToSave, _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

wkbJobInfoWorkbook.Close SaveChanges:=False

Exit Sub

NoTemplateFound:
MsgBox ("File JobInfoTemplate.xlsm Not Found in Path:" & vbCrLf & _
       strPathToJobInfoTemplate)
Exit Sub

End Sub

Function UserNameWindows() As String
    
    Dim lngLen As Long
    Dim strBuffer As String
    
    Const dhcMaxUserName = 255
    
    strBuffer = Space(dhcMaxUserName)
    lngLen = dhcMaxUserName
    If CBool(GetUserName(strBuffer, lngLen)) Then
        UserNameWindows = Left$(strBuffer, lngLen - 1)
    Else
        UserNameWindows = ""
    End If
End Function

' $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
' Method 2 - Using Application.FileDialog
' $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

Private Sub UseFileDialogSave()
    Dim dlgSaveAs As FileDialog
    strFilePathToSave = ""
    Set dlgSaveAs = Application.FileDialog(msoFileDialogSaveAs)
    With dlgSaveAs
        .Show
        If .SelectedItems.Count < 1 Then
            Exit Sub
        End If
        strFilePathToSave = .SelectedItems(1)
    End With
End Sub

' $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
' Additional Example - See Save Portion - This Only Gets The Path And Doesn't Save As Above
' $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

Option Explicit
Dim varFileName As Variant
Public Sub FileOpenAndSave()
' ************************************************************************
' Using The Application.GetOpenFilename Function
' ************************************************************************

varFileName = Application.GetOpenFilename(FileFilter:="Excel File (*.xls),*.xls", FilterIndex:=1, Title:="Choose Excel File To Open")
Call DisplayFileResults

varFileName = Application.GetOpenFilename(FileFilter:="Text Files (*.txt), *.txt, " & _
                                                         "Add-In Files (*.xla), *.xla, " & _
                                                         "Excel Files (*.xls; *.xlsx),*.xls;*.xlsx", FilterIndex:=2, Title:="Enter A FileName To Open")
Call DisplayFileResults

' ************************************************************************
' Using The Application.GetSaveAsFilename Function
' ************************************************************************
varFileName = Application.GetSaveAsFilename(FileFilter:="Excel File (*.xls),*.xls", FilterIndex:=1, Title:="Enter A FileName To Save")
Call DisplayFileResults

varFileName = Application.GetSaveAsFilename(FileFilter:="Excel Files (*.xls; *.xlsx),*.xls;*.xlsx", FilterIndex:=1, Title:="Enter A FileName To Save")
Call DisplayFileResults

varFileName = Application.GetSaveAsFilename(FileFilter:="Visual Basic Files (*.bas; *.txt),*.bas;*.txt", FilterIndex:=1, Title:="Enter A FileName To Save")
Call DisplayFileResults

varFileName = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt, Add-In Files (*.xla), *.xla", FilterIndex:=2, Title:="Enter A FileName To Save")
Call DisplayFileResults

varFileName = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt, " & _
                                                         "Add-In Files (*.xla), *.xla, " & _
                                                         "Excel Files (*.xls; *.xlsx),*.xls;*.xlsx", FilterIndex:=2, Title:="Enter A FileName To Save")
Call DisplayFileResults

End Sub
Private Sub DisplayFileResults()
If varFileName <> False Then
    MsgBox "Save As Filename Is " & varFileName
Else
    MsgBox ("You Did Not Provide A Valid Name")
End If

End Sub