VBA Select file from dialog box (only specific file extensions) - vba

I am trying to write a code where when clicking a commandbutton - it shows a dialog box browser for files and the user can only select ".xlsx" file. WHat I have so far is:
Sub CommandButton_Browse_Click()
Call Set_FileBrowser
'TextBox_OutputDirectory
If Not SelectedFile Is Nothing Then
Me.TextBox_InputDirectory.Text = SelectedFile.Self.Path
End If
End Sub
Sub Set_FileBrowser()
Set shellApp = CreateObject("Shell.Application")
Set SelectedFile = shellApp.BrowseForFolder(0, "Select a file", 16384)
End Sub
It shows the file browser, but it has no filters regarding file format. What's teh correct approach and solution to this problem?

Solution for Solidworks
Adapted from the documentation:
Function SelectXlFile() as String
Dim DialogTitle As String
Dim InitialFileName As String
Dim FileFilter As String
Dim OpenOptions As Long
Dim ConfigName As String
Dim DisplayName As String
Dim fileDisplayState As String
'Example for a single file type:
DialogTitle = "Select an Excel file."
FileFilter = "Excel Files (*.xlsx)|*.xlsx"
'Example for multiple file types:
'DialogTitle = "Select an Excel or Word file."
'FileFilter = "Excel Files (*.xlsx; *.xlsm)|*.xlsx; *xlsm|Word Files (*.docx)|*.docx"
SelectXlFile = Application.SldWorks.GetOpenFileName2(DialogTitle, InitialFileName, _
FileFilter, OpenOptions, ConfigName, DisplayName, fileDisplayState)
End Function
Sub CommandButton_Browse_Click()
'TextBox_OutputDirectory
Me.TextBox_InputDirectory.Text = SelectXlFile()
End Sub
Solution for MS-Office:
Function SelectXlFile() as String
SelectXlFile = Application.GetOpenFilename( _
FileFilter:="Excel Files (*.xlsx),*.xlsx", _
Title:="Select a file.", _
MultiSelect:=False)
End Function
Sub CommandButton_Browse_Click()
'TextBox_OutputDirectory
Me.TextBox_InputDirectory.Text = SelectXlFile()
End Sub

Related

Open the file and save as another name

I want to create a new word file called "xxx_def_xxx" from selected word file called "xxx_docu_xxx".
So I select a file from dialog -> do something -> SaveAs with new file name.
It does work, but I'm getting "run time error 4160: Bad file name" if I select the file created from others, i.e., if the author is not me but another person.
I was struggling with this problem for couple of days but couldn't solve it.
Any help will be really thankful!
Private Sub CommandButton1_Click()
Dim fileOpen As FileDialog
Dim docuName As String, defName As String
Dim docu As Document
Set fileOpen = Application.FileDialog(FileDialogType:=msoFileDialogOpen)
With fileOpen
.Filters.Clear
.Filters.Add "Word Documents", "*.docx*"
.Title = "Select the docu"
.AllowMultiSelect = False
If .Show = -1 Then
docuName = .SelectedItems(1)
Else
Exit Sub
End If
End With
Set docu = Documents.Open(docuName)
'do something: remove or edit some texts in the file
defName = Replace(docu.Name, "docu", "def")
docu.SaveAs docu.Path & "\" & defName
docu.Saved = True
docu.Close
End Sub

Excel VBA - Code to open MS Project File not working

I wrote some code to allow me to select an MS Project file and open it, however when I run the code, nothing happens.
Zero errors, it just exits, any suggestions with what i'm doing wrong here?
Code below
Sub START()
' MS Project variables
Dim Proj As MSProject.Application
Dim NewProj As MSProject.Project
'File Name Variables
Dim FileOpenType As Variant
Dim NewProjFileName As String
Dim NewProjFilePath As String
Dim NewProjFinal As String
'Code to find and open project files
Set Proj = CreateObject("MsProject.Application")
MsgBox ("Please Select MS Project File for Quality Checking")
'Select Project File
FileOpenType = Application.GetOpenFilename( _
FileFilter:="MS Project Files (*.mpp), *.mpp", _
Title:="Select MS Project file", _
MultiSelect:=False)
'Detect if File is selected, if not then stop code
If FileOpenType = False Then
MsgBox ("You Havent Selected a File")
GoTo EndPoint
End If
'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, "\"))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "\") + 1)
'Open Project File
Proj.FileOpen NewProjFilePath & NewProjFileName
EndPoint:
End Sub
Just a couple of notes:
First, since you are using Early Binding to refer to MS-Project, so instead of setting Set Proj = CreateObject("MsProject.Application"), which is used for Late Binding, you can use Set Proj = New MSProject.Application.
Second: since Proj is defined as MSProject.Application, in order to make the MS-Project application visible, it's enough to use Proj.Visible = True.
Code
Option Explicit
Sub START()
' MS Project variables
Dim Proj As MSProject.Application
Dim NewProj As MSProject.Project
'File Name Variables
Dim FileOpenType As Variant
Dim NewProjFileName As String
Dim NewProjFilePath As String
Dim NewProjFinal As String
Set Proj = New MSProject.Application ' since you are using Early binding, you can use this type of setting a new MS-Project instance
MsgBox "Please Select MS Project File for Quality Checking"
'Select Project File
FileOpenType = Application.GetOpenFilename( _
FileFilter:="MS Project Files (*.mpp), *.mpp", _
Title:="Select MS Project file", _
MultiSelect:=False)
If FileOpenType = False Then
MsgBox "You Havent Selected a File"
Exit Sub ' <-- use Exit Sub instead of GoTo EndPoint
End If
'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, "\"))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "\") + 1)
'Open Project File
Proj.FileOpen NewProjFilePath & NewProjFileName
Proj.Visible = True ' <-- Set MS-Project as visible application
End Sub
Resolved by adding the following line, edited code to show
Proj.Application.Visible = True

Excel VBA code For opening Excel xlsx File on a daily Basis with date in his name

I have 2 files that I want to merge to one report. Both files are in different folders and they are alone in their folder.
My problem is that when I dim each workbook as a variable I need to put a path with the name of the file.
I want that the path will stay and every time I run the Macro it will dim the current workbook in the file as "x"
Name of file for example - Clean room GSS parts - tracking file 17.05.2017
Here is my code:
Set x = Workbooks.Open("C:\Users\rosipov\Desktop\eliran\MFG - GSS\GSS\Clean room GSS parts - tracking file 17.05.2017.xlsx")
Thanks for helping.
You can convert the date of a cell, input or NOW to a string with the format you use in the filename:
FORMAT(NOW(),"dd.mm.yyyy")
Now you can use this when opening the file:
Set x = Workbooks.Open("C:\Users\rosipov\Desktop\eliran\MFG - GSS\GSS\Clean room GSS parts - tracking file " & FORMAT(NOW(),"dd.mm.yyyy") & ".xlsx")
Remember that you can use other values than the current date NOW().
You could perhaps, ask the user to select the file that you are wanting to select using the File Dialog Box.
Option Explicit
Public Enum FileDialogType
msoFileDialogOpen = 1
msoFileDialogSaveAs = 2
msoFileDialogFilePicker = 3
msoFileDialogFolderPicker = 4
End Enum
Public Function OpenTargetWBExample()
Dim FilePath As String: FilePath = FileDialog(msoFileDialogFilePicker, "Select workbook to open")
If Len(FilePath) = 0 Then Exit Function
Dim TargetWB As Workbook: Set TargetWB = Workbooks.Open(FilePath)
'Extra code goes here
Set TargetWB = Nothing
End Function
Public Function FileDialog(ByVal DialogType As FileDialogType, Optional ByVal DialogTitle As String, _
Optional MultiSelect As Boolean, Optional ByVal FileFilter As String) As String
'If MultiSelect then outputs files in the following format: "File1;File2;File3"
'Custom File Extension Filter Format: "File Description 1~File Extension Filter 1|File Description 2~File Extension Filter 2"
Dim FileDialogObject As FileDialog: Set FileDialogObject = Application.FileDialog(DialogType)
Dim Index As Long, Filters() As String, Element() As String
Dim SelectedFile As Variant
With FileDialogObject
If Len(DialogTitle) > 0 Then .Title = DialogTitle
.AllowMultiSelect = MultiSelect
If Len(FileFilter) > 0 Then
Filters = Split(FileFilter, "|")
For Index = 0 To UBound(Filters)
Element = Split(Filters(Index), "~")
.Filters.Add Element(0), Element(1), (.Filters.Count + 1)
Next Index
End If
.FilterIndex = 0
.Show
.Filters.Clear
For Each SelectedFile In .SelectedItems
FileDialog = FileDialog & CStr(SelectedFile) & ";"
Next SelectedFile
If Len(FileDialog) > 0 Then FileDialog = Left(FileDialog, Len(FileDialog) - 1)
End With
Set FileDialogObject = Nothing
End Function
since there is only one file in the directory
dim aaa as String
aaa = ""C:\Users\rosipov\Desktop\eliran\MFG - GSS\GSS\"
Set x = Workbooks.Open(aaa & Dir(aaa))

How to get the browse file path in text box using VBA?

How to get the browse file name into text box ? if get the file path, how to split the file name?
I tried application.GetOpenFilename("Text Files(*.txt),*.txt")
Please advise to display into the text box and how to split the exact file name only to read the text file?
Don't waste your time reinventing the wheel: the FileSystemObject will do this for you.
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Sheet1.TextBox1.Text = FSO.GetFilename("C:\mydir\myfile.dat")
The textbox now contains the text myfile.dat.
The Dir function will give you the file name as long as it's a file that exists - and yours will be if you use GetOpenFilename.
Sub GetFileName()
Dim sFullName As String
Dim sFileName As String
sFullName = Application.GetOpenFilename("*.txt,*.txt")
sFileName = Dir(sFullName)
Debug.Print sFullName, sFileName
End Sub
Here is a VBA routine to return the file name stripped of its path. Its easily modified to return the path instead, or both.
'====================================================================================
' Returns the file name without a path via file open dialog box
'====================================================================================
' Prompts user to select a file. Which ever file is selected, the function returns
' the filename stripped of the path.
Function GetAFileName() As String
Dim someFileName As Variant
Dim folderName As String
Dim i As Integer
Const STRING_NOT_FOUND As Integer = 0
'select a file using a dialog and get the full name with path included
someFileName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If someFileName <> False Then
'strip off the folder path
folderName = vbNullString
i = 1
While STRING_NOT_FOUND < i
i = InStr(1, someFileName, "\", vbTextCompare) 'returns position of the first backslash "\"
If i <> STRING_NOT_FOUND Then
folderName = folderName & Left(someFileName, i)
someFileName = Right(someFileName, Len(someFileName) - i)
Else 'no backslash was found... we are done
GetAFileName = someFileName
End If
Wend
Else
GetAFileName = vbNullString
End If
End Function
Easiest way is to simply read from the final "\";
tbx.text = mid$(someFileName, 1 + InStrRev(someFileName, "\"), Len(someFileName))
Button1 click
OpenFileDialog1.ShowDialog()
Me.TextBox1.Text = OpenFileDialog1.FileName
End Sub
Textbox1 change
Dim File As System.IO.FileInfo
File = My.Computer.FileSystem.GetFileInfo(TextBox1.Text)
Dim Path As String = File.DirectoryName
TextBox2.Text = Path
Dim fileName As String = File.Name
TextBox3.Text = fileName
End Sub

using Application.FileDialog to rename a file in VBA

Using VBA. My script moves a file into a directory. If that filename already exists in the target directory, I want the user to be prompted to rename the source file (the one that's being moved) before the move is executed.
Because I want the user to know what other files are in the directory already (so they don't choose the name of another file that's already there), my idea is to open a FileDialog box listing the contents of the directory, so that the user can use the FileDialog box's native renaming capability. Then I'll loop that FileDialog until the source file and target file names are no longer the same.
Here's some sample code:
Sub testMoveFile()
Dim fso As FileSystemObject
Dim file1 As File
Dim file2 As File
Dim dialog As FileDialog
Set fso = New FileSystemObject
fso.CreateFolder "c:\dir1"
fso.CreateFolder "c:\dir2"
fso.CreateTextFile "c:\dir1\test.txt"
fso.CreateTextFile "c:\dir2\test.txt"
Set file1 = fso.GetFile("c:\dir1\test.txt")
Set file2 = fso.GetFile("c:\dir2\test.txt")
Set dialog = Application.FileDialog(msoFileDialogOpen)
While file1.Name = file2.Name
dialog.InitialFileName = fso.GetParentFolderName(file2.Path)
If dialog.Show = 0 Then
Exit Sub
End If
Wend
file1.Move "c:\dir2\" & file1.Name
End Sub
But when I rename file2 and click 'OK', I get an error:
Run-time error '53': File not found
and then going into the debugger shows that the value of file2.name is <File not found>.
I'm not sure what's happening here--is the object reference being lost once the file's renamed? Is there an easier way to let the user rename from a dialog that shows all files in the target directory? I'd also like to provide a default new name for the file, but I can't see how I'd do that using this method.
edit: at this point I'm looking into making a UserForm with a listbox that gets populated w/ the relevant filenames, and an input box with a default value for entering the new name. Still not sure how to hold onto the object reference once the file gets renamed, though.
Here's a sample of using Application.FileDialog to return a filename that the user selected. Maybe it will help, as it demonstrates getting the value the user provided.
EDIT: Modified to be a "Save As" dialog instead of "File Open" dialog.
Sub TestFileDialog()
Dim Dlg As FileDialog
Set Dlg = Application.FileDialog(msoFileDialogSaveAs)
Dlg.InitialFileName = "D:\Temp\Testing.txt" ' Set suggested name for user
' This could be your "File2"
If Dlg.Show = -1 Then
Dim s As String
s = Dlg.SelectedItems.Item(1) ` Note that this is for single-selections!
Else
s = "No selection"
End If
MsgBox s
End Sub
Edit two: Based on comments, I cobbled together a sample that appears to do exactly what you want. You'll need to modify the variable assignments, of course, unless you're wanting to copy the same file from "D:\Temp" to "D:\Temp\Backup" over and over. :)
Sub TestFileMove()
Dim fso As FileSystemObject
Dim SourceFolder As String
Dim DestFolder As String
Dim SourceFile As String
Dim DestFile As String
Set fso = New FileSystemObject
SourceFolder = "D:\Temp\"
DestFolder = "D:\Temp\Backup\"
SourceFile = "test.txt"
Set InFile = fso.GetFile(SourceFolder & SourceFile)
DestFile = DestFolder & SourceFile
If fso.FileExists(DestFile) Then
Dim Dlg As FileDialog
Set Dlg = Application.FileDialog(msoFileDialogSaveAs)
Dlg.InitialFileName = DestFile
Do While True
If Dlg.Show = 0 Then
Exit Sub
End If
DestFile = Dlg.Item
If Not fso.FileExists(DestFile) Then
Exit Do
End If
Loop
End If
InFile.Move DestFile
End Sub
Here's some really quick code that I knocked up but basically looks at it from a different angle. You could put a combobox on a userform and get it to list the items as the user types. Not pretty, but it's a start for you to make more robust. I have hardcoded the directory c:\ here, but this could come from a text box
Private Sub ComboBox1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger,
ByVal Shift As Integer)
Dim varListing() As Variant
Dim strFilename As String
Dim strFilePart As String
Dim intFiles As Integer
ComboBox1.MatchEntry = fmMatchEntryNone
strFilePart = ComboBox1.Value
strFilename = Dir("C:\" & strFilePart & "*.*", vbDirectory)
Do While strFilename <> ""
intFiles = intFiles + 1
ReDim Preserve varListing(1 To intFiles)
varListing(intFiles) = strFilename
strFilename = Dir()
Loop
On Error Resume Next
ComboBox1.List() = varListing
On Error GoTo 0
ComboBox1.DropDown
End Sub
Hope this helps. On error resume next is not the best thing to do but in this example stops it erroring if the variant has no files