VBA to open SaveAs dialog box in specific folder

Holley

Board Regular
Joined
Dec 11, 2019
Messages
155
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
Hello again! Once again I come asking for your help. I have a macro that does everything I want it to, until the end. The file is being opened on a personal drive (D: ), but I would like to save it on a network drive (G: ). Everything works, even converts from .txt to .xlsx except it keeps opening the dialog box on the personal drive (Drive D where the file originates). This will be ran regularly and will need to be saved on the G drive with the only thing changing is the file name, which is why I want the prompt to open. Any help would be most appreciated. Below is the code I am using. Thank you in advance!!

VBA Code:
Sub KP()
'
' KP Macro
'
' Keyboard Shortcut: Ctrl+Shift+P
'
    Cells.Select
    Selection.Columns.AutoFit
    ActiveSheet.Range("$A$1:$G$126").RemoveDuplicates Columns:=4, Header:=xlYes
    ActiveWorkbook.Worksheets("CUST601").sort.SortFields.Clear
    ActiveWorkbook.Worksheets("CUST601").sort.SortFields.Add2 Key:=Range( _
        "E2:E126"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets("kohl601").sort
        .SetRange Range("A1:G126")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Columns("F:F").Select
    Selection.Style = "Currency"
    Range("F3").Select
    Selection.End(xlDown).Select
     Cells.SpecialCells(xlCellTypeVisible)(1).Select
     ChDir "G:\"
    Dim wb As Boolean
       wb = Application.Dialogs(xlDialogSaveAs).Show(File_Name, 51)
End Sub
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
Option 1
VBA Code:
ChDrive "G:\"   'To set the default drive
ChDir "G:\"       'To set the default folder on that drive
Dim wb As Boolean

Option 2
VBA Code:
    Dim wb As Boolean
    File_Name = "G:\" & File_Name
    wb = Application.Dialogs(xlDialogSaveAs).Show(File_Name, 51)

Option 3 - Sklip Dialog Box
VBA Code:
ThisWorkbook.SaveAs("G:\" & File_Name & ".xlsx")
 
Upvote 0
Thanks!! I've tried both Opt 1 and 2, with the same results. When I saw
VBA Code:
ChDrive "G:\"
I thought that would do it and felt dumb that I didn't include to change the drive, but that didn't work either. I do need the dialog box as the file name will change each time.
 
Upvote 0
Thanks!! I've tried both Opt 1 and 2, with the same results. When I saw
VBA Code:
ChDrive "G:\"
I thought that would do it and felt dumb that I didn't include to change the drive, but that didn't work either. I do need the dialog box as the file name will change each time.
"G" is a network drive. Not sure if that is causing the issue...
 
Upvote 0
All 3 worked for me with G being a network drive. Try this to see if the drive is being changed (I have no idea why it would not change):

VBA Code:
ChDrive "G:\"   'To set the default drive (only first letter is read)
ChDir "G:\"       'To set the default folder on that drive
msgbox CurDir    'Show the current drive:\folderpath

Is the first range specified never going to change?
This would select the entire block around A1:
VBA Code:
ActiveSheet.Range("A1").CurrentRegion.RemoveDuplicates Columns:=4, Header:=xlYes

Regarding Option 3, if the name does not depend on files already in the save folder, you could popup an input box and use the non-zero length reply to populate

VBA Code:
Sub Option3()

    Dim File_Name
    Dim sSaveLocation
    
    sSaveLocation = "G:\SomeFolder\"
    
    File_Name = InputBox("Enter the save filename for the workbook in G", "Enter Filename")
    If Len(File_Name) > 0 Then
        ThisWorkbook.SaveAs (sSaveLocation & File_Name & ".xlsx")
    Else
        MsgBox "No filename entered.  Edited workbook not saved.", vbCritical, "No Filename Entered"
    End If
    
End Sub
 
Upvote 0
Thanks again for your help! The below does show the G drive when ran
VBA Code:
ChDrive "G:\"   'To set the default drive (only first letter is read)
ChDir "G:\"       'To set the default folder on that drive
msgbox CurDir    'Show the current drive:\folderpath
But when trying to save, it always reverts back to the D Drive.

Option 3 I really like a lot! Seems to take me to the G drive, but I get a run time 1004 error. The original file is a .txt that we are saving as .xlsx. This would be the perfect fix.
View attachment 74546 View attachment 74547
 
Upvote 0
I really do not understand why the default changes back. Try this:

Sub Option3v1()

Dim File_Name
Dim sSaveLocation

sSaveLocation = "G:\SomeFolder\"
File_Name = InputBox("Enter the save filename for the workbook in G", "Enter Filename")

If Len(File_Name) > 0 Then
ActiveSheet.Copy 'Copies current worksheet to new workbook and that workbook becomes the ActiveWorkbook
'It has never been stored before and SHOULD have no memory of a save location
ActiveWorkbook.SaveAs _
Filename:=sSaveLocation & File_Name & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Else
MsgBox "No filename entered. Edited workworksheet not saved as new workbook.", vbCritical, "No Filename Entered"
End If

End Sub
 
Upvote 0
Thanks again, but I got an error message that it couldn't save the file type. I kept playing with it and was able to get it to run by changing the sSaveLocation="\\network location" versus the drive letter. Once that was changed, it worked perfectly. I'm guessing may be a security setting possibly?

Thank you so much for your help! I love the way Option 3 works and also appreciate the suggestion below
VBA Code:
ActiveSheet.Range("A1").CurrentRegion.RemoveDuplicates Columns:=4, Header:=xlYes

Here is my complete code, need to clean it up a bit, but it works

VBA Code:
Sub KP()
'
' KP Macro
'
' Keyboard Shortcut: Ctrl+Shift+P
'

    ActiveSheet.Name = "sheet1"
    SaveToDirectory = "G:\ "
    Cells.Select
    Selection.Columns.AutoFit
ActiveSheet.Range("A1").CurrentRegion.RemoveDuplicates Columns:=4, Header:=xlYes
    ActiveWorkbook.Worksheets("sheet1").sort.SortFields.Clear
    ActiveWorkbook.Worksheets("sheet1").sort.SortFields.Add2 Key:=Range( _
        "E2:E126"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets("sheet1").sort
        .SetRange Range("A1:G126")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
        Columns("F:F").Select
        Selection.Style = "Currency"
        Range("F3").Select
        Selection.End(xlDown).Select
        Cells.SpecialCells(xlCellTypeVisible)(1).Select
    '  SetCurrentDirectoryA "\\server\share\share folders\Reports "
    '  ChDrive "G:\"   'To set the default drive (only first letter is read)
    '  ChDir "G:\"       'To set the default folder on that drive
    '  wb = Application.Dialogs(xlDialogSaveAs).Show(File_Name, 51)
'MsgBox CurDir    'Show the current drive:\folderpath
 'sSaveLocation = "G:\”
    
    File_Name = InputBox("Enter the save filename format must be 'date 00-00-00 Report'", "Enter Filename")
    sSaveLocation = "\\server\share\share folders\Reports\"
    
  '  File_Name = InputBox("Enter the save filename for the workbook in P", "Enter Filename")
    If Len(File_Name) > 0 Then
        'ThisWorkbook.SaveAs (sSaveLocation & File_Name & ".xlsx")
        'ActiveWorkbook.SaveAs fileName:=fileName 'default ext
         ActiveWorkbook.SaveAs (sSaveLocation & File_Name & ".xlsx")
         'ActiveWorkbook.SaveAs fileName:=SaveToDirectory & File_Name & ".xlsx", FileFormat:=51
    Else
        MsgBox "No filename entered.  Edited workbook not saved.", vbCritical, "No Filename Entered"
    End If
End Sub
 
Upvote 0
Glad you got it to work. Added a few things and had a question or 2.

VBA Code:
Option Explicit     'Tools | Options | Require Variable Declarations     will automatically add this to all new modules

Sub KP()
'
' KP Macro
'
' Keyboard Shortcut: Ctrl+Shift+P
'
    'I always declare variables - it has saved me a lot of time over the years
    Dim SaveToDirectory As String
    Dim lLastDataRow As Long
    Dim sSaveLocation As String
    Dim File_Name As String
    Dim sDateString As String
    
                                'I also use prefixes to distinguish the variable type, some folks do not
                                ' this is an article the discusses pros and cons for 'Hungarian notation'
                                'https://softwareengineering.stackexchange.com/questions/39771

    ActiveSheet.Name = "sheet1"
    SaveToDirectory = "G:\ "
    
    'Most things do not have to be selected to be acted upon (some graph elements are an exception)
    'Replace next 2 lines with 3rd
'    Cells.Select
'    Selection.Columns.AutoFit
    Cells.Columns.AutoFit

    With ActiveSheet
        .AutoFilterMode = False  'To make sure the sheet was not left in a filtered state
        .Range("A1").CurrentRegion.RemoveDuplicates Columns:=4, Header:=xlYes
    End With
    'Using the With statement and objects starting with a . to reference the with statement
    '  processes more quickly.  Not significant for a single pass, but can be very important
    '  inside a processing loop
    With ActiveWorkbook.Worksheets("sheet1")
        lLastDataRow = .Cells(.Rows.Count, 1).End(xlUp).Row  'Find the last row with data in column 1 (A)
        .Sort.SortFields.Clear
        'Changed the last row from a fixed number to the actual last row
        .Sort.SortFields.Add Key:=Range("E2:E" & lLastDataRow), _
            SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With .Sort
            .SetRange ActiveWorkbook.Worksheets("sheet1").Range("A1:G" & lLastDataRow)
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
'        Columns("F:F").Select
'        Selection.Style = "Currency"
        .Columns("F:F").Style = "Currency"
        
        'Next few rows is a bit confusing, unless you have filtered the data and are doing something
        '  with the visible cells
'        Range("F3").Select             'This will select F3
'        Selection.End(xlDown).Select   'This will select the cell above the next blank cell in column F
'        Cells.SpecialCells(xlCellTypeVisible)(1).Select    'This will select A1

        'Not sure what you are trying to do here, but here are some possibilities

        'This will select all visible cells in column F from F3 down
        .Range(.Range("F3"), .Cells(.Rows.Count, 6).End(xlUp)).SpecialCells(xlCellTypeVisible).Select
        
        'But if it is a 'normal' data set with the  all used columns for all used rows having some
        '  this will also work to select all visible cells in column F from F3 down
        .Range("F3:F" & lLastDataRow).Select
        
        'What is the intent behind this line?
        .Cells.SpecialCells(xlCellTypeVisible)(1).Select
        
        
    '  SetCurrentDirectoryA "\\server\share\share folders\Reports "
    '  ChDrive "G:\"   'To set the default drive (only first letter is read)
    '  ChDir "G:\"       'To set the default folder on that drive
    '  wb = Application.Dialogs(xlDialogSaveAs).Show(File_Name, 51)
    'MsgBox CurDir    'Show the current drive:\folderpath
    'sSaveLocation = "G:\”
       
       'I am not sure if your date is in a YMD format, but that format makes it easier to sort.
       'Also ISO 8601 (see Wikipedia) and I both like yyyy-mm-dd for a standard date format.
       sDateString = Format(Now(), "yy-mm-dd")
       File_Name = InputBox("Enter the save filename format must be 'date 00-00-00 Report'", "Enter Filename", _
           "date " & sDateString & " Report")
       sSaveLocation = "\\server\share\share folders\Reports\"
    
  '  File_Name = InputBox("Enter the save filename for the workbook in P", "Enter Filename")
        If Len(File_Name) > 0 Then
            'ThisWorkbook.SaveAs (sSaveLocation & File_Name & ".xlsx")
            'ActiveWorkbook.SaveAs fileName:=fileName 'default ext
             ActiveWorkbook.SaveAs (sSaveLocation & File_Name & ".xlsx")
             'ActiveWorkbook.SaveAs fileName:=SaveToDirectory & File_Name & ".xlsx", FileFormat:=51
        Else
            MsgBox "No filename entered.  Edited workbook not saved.", vbCritical, "No Filename Entered"
        End If
    End With
End Sub
 
Upvote 0
Solution
Oh my gosh! This is absolutely perfect! I really appreciate your explanations on the code! I recorded my steps then attempted to tweak it for a weekly process. You have also helped me learn a bit more about coding. Thank you so much for all of your help!
 
Upvote 0

Forum statistics

Threads
1,223,903
Messages
6,175,289
Members
452,631
Latest member
a_potato

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top