Get file name & destination of VBA save dialog box - excel

I currently have set up a dialog box which will allow a user to pick a file destination. After the destination is picked, you can input a name of the file, and will set "FileSaveName" to the full path like C:\user\desktop\test.xml I am new to this tool that is offered through VBA. Is it possible to obtain the file name and the extension separately? Or will I need to manually trim characters from the string?
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Text Files (*.xml), *.xml")
If fileSaveName <> False Then
MsgBox "File path and file name: " & fileSaveName
'MsgBox "File path: " & filepath
'MsgBox "File name: " & filename
End If

You can use the Windows Scripting objects:
Dim objFS as Object
Dim objFile as Object
Dim strPath as String
Dim strFile as String
Dim strExt as String
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Text Files (*.xml), *.xml")
If fileSaveName <> False Then
MsgBox "File path and file name: " & fileSaveName
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(fileSaveName)
strFile = objFile.Name
strPath = objFile.ParentFolder
strExt = objFS.GetExtensionName(fileSaveName)
MsgBox "File path: " & strPath
MsgBox "File name: " & strFile
MsgBox "File extension: " & strExt
' Remove references
Set objFile = Nothing
Set objFS = Nothing
End If
Good reference here

you could do like this
Sub main()
Dim fileSaveName As Variant
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Text Files (*.xml), *.xml")
If fileSaveName <> False Then
MsgBox "File path and file name: " & fileSaveName
MsgBox "File path: " & GetFilePath(fileSaveName)
MsgBox "File name: " & GetFileName(fileSaveName)
MsgBox "File extension: " & GetFileExt(fileSaveName)
End If
End Sub
Function GetFilePath(fileFullPath As Variant) As String
GetFilePath = Left(fileFullPath, InStrRev(fileFullPath, "\"))
End Function
Function GetFileName(fileFullPath As Variant) As String
GetFileName = Right(fileFullPath, Len(fileFullPath) - InStrRev(fileFullPath, "\"))
End Function
Function GetFileExt(fileFullPath As Variant) As String
Dim fileName As String
fileName = GetFileName(fileFullPath)
GetFileExt = Right(fileName, Len(fileName) - InStrRev(fileName, "."))
End Function

Related

to move files from one folder to another using VBA

I have a code which can transfer the Excel files from one folder to another but i would like to update the code so that it can move all the files (.xml, .txt, .pdf, etc.) from one folder to another.
Sub MoveFiles()
Dim sourceFolderPath As String, destinationFolderPath As String
Dim FSO As Object, sourceFolder As Object, file As Object
Dim fileName As String, sourceFilePath As String, destinationFilePath As String
Application.ScreenUpdating = False
sourceFolderPath = "E:\Source"
destinationFolderPath = "E:\Destination"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set sourceFolder = FSO.GetFolder(sourceFolderPath)
For Each file In sourceFolder.Files
fileName = file.Name
If InStr(fileName, ".xlsx") Then ' Only xlsx files will be moved
sourceFilePath = file.Path
destinationFilePath = destinationFolderPath & "\" & fileName
FSO.MoveFile Source:=sourceFilePath, Destination:=destinationFilePath
End If ' If InStr(sourceFileName, ".xlsx") Then' Only xlsx files will be moved
Next
'Don't need set file to nothing because it is initialized in for each loop
'and after this loop is automatically set to Nothing
Set sourceFolder = Nothing
Set FSO = Nothing
End Sub
can you please help
Move Files Using MoveFile
You would get greater control of things by using CopyFile and DeleteFile instead of MoveFile.
Using Dir, FileCopy, and Kill, instead of the FileSystemObject object and its methods, would make it simpler and also faster.
Option Explicit
Sub MoveFilesTEST()
Const sFolderPath As String = "E:\Source"
Const dFolderPath As String = "E:\Destination"
Const FilePattern As String = "*.*"
MoveFiles sFolderPath, dFolderPath, FilePattern
End Sub
Sub MoveFiles( _
ByVal SourceFolderPath As String, _
ByVal DestinationFolderPath As String, _
Optional ByVal FilePattern As String = "*.*")
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(SourceFolderPath) Then
MsgBox "The source folder path '" & SourceFolderPath _
& "' doesn't exist.", vbCritical
Exit Sub
End If
If Not fso.FolderExists(DestinationFolderPath) Then
MsgBox "The destination folder path '" & DestinationFolderPath _
& "' doesn't exist.", vbCritical
Exit Sub
End If
Dim apSep As String: apSep = Application.PathSeparator
Dim sPath As String: sPath = SourceFolderPath
If Left(sPath, 1) <> apSep Then sPath = sPath & apSep
Dim sFolder As Object: Set sFolder = fso.GetFolder(sPath)
If sFolder.Files.Count = 0 Then
MsgBox "There are no files in the source folder '" & sPath & "'.", _
vbExclamation
Exit Sub
End If
Dim dPath As String: dPath = DestinationFolderPath
If Left(dPath, 1) <> apSep Then dPath = dPath & apSep
Dim dFolder As Object: Set dFolder = fso.GetFolder(dPath)
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim sFile As Object
Dim dFilePath As String
Dim ErrNum As Long
Dim MovedCount As Long
Dim NotMovedCount As Long
For Each sFile In sFolder.Files
dFilePath = dPath & sFile.Name
If fso.FileExists(dFilePath) Then
dict(sFile.Path) = Empty
NotMovedCount = NotMovedCount + 1
Else
On Error Resume Next
fso.MoveFile sFile.Path, dFilePath
ErrNum = Err.Number
' e.g. 'Run-time error '70': Permission denied' e.g.
' when the file is open in Excel
On Error GoTo 0
If ErrNum = 0 Then
MovedCount = MovedCount + 1
Else
dict(sFile.Path) = Empty
NotMovedCount = NotMovedCount + 1
End If
End If
Next sFile
Dim Msg As String
Msg = "Files moved: " & MovedCount & "(" & NotMovedCount + MovedCount & ")"
If NotMovedCount > 0 Then
Msg = Msg & vbLf & "Files not moved:" & NotMovedCount & "(" _
& NotMovedCount + MovedCount & ")" & vbLf & vbLf _
& "The following files were not moved:" & vbLf _
& Join(dict.keys, vbLf)
End If
MsgBox Msg, IIf(NotMovedCount = 0, vbInformation, vbCritical)
End Sub

Suppress Save as pdf dialog box

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

How to fix "Bad File Name or Number" error when saving an Excel file via macro?

I need to save my excel file using a macro and I am making use of an old macro I made a while ago - which worked just fine. But now, I am getting an error which I don't seem to understand all to well.
Code:
Option Explicit
Sub SaveFile()
Dim strDir As String, saveDate As String, userMachine As String, Filename As String, yearDate As String, monthDate As String, filePath As String
Dim ws1 As Workbook
Set ws1 = Workbooks("Template.xlsm")
Application.DisplayAlerts = False
saveDate = "01/02/2019"
yearDate = Year(saveDate)
monthDate = Format(saveDate, "MMMM")
saveDate = Format(saveDate, "dd-mm-yyyy")
userMachine = "User - 12345"
strDir = "C:\user12345\desktop\Final Results\" & yearDate & "\" & monthDate & "\" & Format(saveDate, "dd-mm-yyyy") & "\"
filePath = ""
Filename = userMachine & " - " & saveDate & ".xlsx"
filePath = Dir(strDir & Filename)
If Dir(strDir, vbDirectory) = "" Then
MkDir strDir
If filePath = "" Then
ws1.SaveAs Filename:=filePath, FileFormat:=51, CreateBackup:=False
Else
MsgBox filePath & " Execution File Exists"
End If
Else
If filePath = "" Then
ws1.SaveAs Filename:=filePath, FileFormat:=51, CreateBackup:=False
Else
MsgBox filePath & " Execution File Exists"
End If
End If
End Sub
The error is on this line filePath = Dir(strDir & Filename) and the error is:
Bad File Name or Number
As far as I can see, my name for the file meets the requirements to save it so I am at a total loss here.
The original code I had was this:
strDir = "C:\username\desktop\" & Format(DateAdd("d", -1, Date), "dd_mm_YY") & "\"
FilePath = Dir(strDir & "myFile.xlsx")
Bad File Name or Number means that the string you are using to save the file is not valid.
You could replace the hardcoded string to your desktop with a relative reference from a function, such as:
Function getDeskTopPath() As String
'Get Desktop path as string
'Command can be exchanged for other information... see list below
'AllUsersDesktop
'AllUsersStartMenu
'AllUsersPrograms
'AllUsersStartup
'Desktop
'Favorites
'Fonts
'MyDocuments
'NetHood
'PrintHood
'Programs
'Recent
'SendTo
'StartMenu
'Startup
'Templates
Dim oShell As Object
Set oShell = CreateObject("Wscript.Shell")
getDeskTopPath = oShell.SpecialFolders("Desktop")
Set oShell = Nothing
End Function

Excel VBA Form control: Opening/creating an Excel file

I'd to create check if a file is exists using the shipNo and FilePath. If not, copy master.xls and rename the file according to shipNo. In all cases open the file afterwards.
Private Sub PDFButton_Click()
On Error Resume Next
Dim SourceFile As String, destFile As String, sourceExtension, shipNo As String
'Initialize variables
shipNo = Range("D4").Value
FilePath = "C:\Users\*\Documents\QueueRecord\"
SourceFile = "C:\Users\*\Documents\QueueRecord\Gen master.xls\"
If (destFile) = "" Then
Dim fso, createText As FileSystemObject
Set fso = New Scripting.FileSystemObject
fso.CopyFile SourceFile, FilePath & "SampleFileCopy.xls\"
Set createText = fso.CreateTextFile(FilePath, True, True)
createText.Write "success"
createText.Close
If fso.FileExists(FilePath & "SampleFileCopy.xls\") Then
MsgBox "Success"
End If
End If
ActiveWorkbook.FollowHyperlink ("C:\Users\*\Documents\QueueRecord\" + shipNo + ".xls\")
End Sub
In my tests SampleFileCopy.xls is never created, nor is the textFile created.
destFile will always be empty the way you have it written. I'm assuming you want the line to look like:
If dir(FilePath & shipNo & ".xls") = "" Then
Also, remove all the back slashes after the full file paths.
this:
"C:\Users\*\Documents\QueueRecord\Gen master.xls\"
should be this:
Environ("userprofile") & "\Documents\QueueRecord\Gen master.xls"
Also, as stated in the comments, remove the "on error resume next" so you know where the code is breaking.
Full code below, based on the assumption that destFile is supposed to be filepath and shipNo:
Private Sub PDFButton_Click()
Dim SourceFile As String, destFile As String, sourceExtension, shipNo As String
'Initialize variables
shipNo = Range("D4").Value
FilePath = Environ("userprofile") & "\Documents\QueueRecord\"
SourceFile = Environ("userprofile") & "\Documents\QueueRecord\Gen master.xls"
If Dir(FilePath & shipNo & ".xls", vbDirectory) = "" Then
Dim fso As FileSystemObject
Set fso = New Scripting.FileSystemObject
fso.CopyFile SourceFile, FilePath & "SampleFileCopy.xls"
'create text file
TextFile = FreeFile
Open FilePath & shipNo & ".txt" For Output As TextFile
Print #TextFile, "success";
Close TextFile
If fso.FileExists(FilePath & "SampleFileCopy.xls") Then
MsgBox "Success"
End If
End If
ActiveWorkbook.FollowHyperlink (Environ("userprofile") & "\Documents\QueueRecord\" & shipNo & ".xls")
End Sub

VBA Saving to CurDir on Mapped Drive

I created a macro that needs some tweaking but cannot find an answer to one part. Based on the user input of officename, it opens up the SaveAs dialog box and creates a folder in the current directory of the file + today's date. When saved locally this works fine. When the file is moved to the mapped drive the save as dialog box opens to my local downloads folder. I've tried a few things but all have the same result.
When I debug and print the path it is correct. I believe the problem lies somewhere with how I'm using the FileSystemObject and the ChDir even though from what I've read these should be working fine the way they're being used. The complete sub is pasted below.
Sub SaveAs()
Dim file_name As Variant
Dim xdir As String
Dim fso
Dim saveDate As String
Set fso = CreateObject("Scripting.FileSystemObject")
saveDate = Date
saveDate = Replace(saveDate, "/", ".")
'Debug.Print "Test" & " "; officeName <-- good
Fname = officename & " " & Date
Fname = Replace(Fname, "/", "-")
Debug.Print Fname <-- good
xdir = ThisWorkbook.Path & "\" & officename
Debug.Print xdir <-- good
If Not fso.FolderExists(xdir) Then
fso.CreateFolder (xdir)
End If
ChDir (xdir)
' Get the file name.
file_name = Application.GetSaveAsFilename(Fname, _
FileFilter:="Excel Macro-Enabled Workbook,*.xlsm,All Files,*.*", _
Title:="Save As File Name")
' See if the user canceled.
If file_name = False Or "False.xls" Then Exit Sub
Updated code below is now working beautifully on all machines! Thanks for the input!
ChDir (xdir)
Sub SaveAs()
Dim file_name As Variant
Dim xdir As String
Dim fso
Dim saveDate As String
Dim driveLetter As String <-- NEW VARIABLE
Set fso = CreateObject("Scripting.FileSystemObject")
saveDate = Date
saveDate = Replace(saveDate, "/", ".")
'Debug.Print "Test" & " "; officeName <-- good
Fname = officename & " " & Date
Fname = Replace(Fname, "/", "-")
Debug.Print Fname <-- good
xdir = ThisWorkbook.Path & "\" & officename
Debug.Print xdir <-- good
If Not fso.FolderExists(xdir) Then
fso.CreateFolder (xdir)
End If
////new code
driveLetter = Left(xdir, 1)
ChDrive (driveLetter)
////new code
ChDir (xdir)
' Get the file name.
file_name = Application.GetSaveAsFilename(Fname, _
FileFilter:="Excel Macro-Enabled Workbook,*.xlsm,All Files,*.*", _
Title:="Save As File Name")
' See if the user canceled.
If file_name = False Or "False.xls" Then Exit Sub

Resources