How to get the browse file path in text box using VBA? - 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

Related

LibreOffice how to get filepicker multiple file selection data

In LibreOffice 4.2 I am trying to open the file picker and select multiple files (which I succeeded), and then to transfer the names (and path) of those files to a variable (or array, does not matter).
Although I can open the file picker and select multiple files, I can get the file name and path of only one file (the first one). And I couldn't find any way to get the others.
I am using the following code:
Sub TakeFile()
Dim FileNames(0 to 100) as String
FileNames() = fImportLocalFile()
Msgbox FileNames
End Sub
Function fImportLocalFile() 'as String
' FJCC: Can't define the function as returning a String because now it returns an array
'this function opens a system file open dialog box and allows the
' user to pick a file from thier computer to open into the
' document for processing
'stores the filedialog object
Dim oFileDialog as Object
'stores the returned result of the activation of the dialog box
Dim iAccept as Integer
'stores the returned file name/path from the file dialog box
Dim sPath as String
'stores the set default path for the dialog box
Dim InitPath as String
'stores the types of files allowed in the filedialog
Dim sFilterNames as String
'setup the filters for the types of files to allow in the dialog
sFilterNames = "*.csv; *.txt; *.odt; *.ods; *.xls; *.xlt; *.xlsx"
'create the dialog box as a Windows File Dialog
oFileDialog = CreateUnoService("com.sun.star.ui.dialogs.FilePicker")
'set the filters for the dialog
oFileDialog.AppendFilter("Supported files", sFilterNames)
'set the path as blank
InitPath = ""
'add the default path to the dialog
oFileDialog.setDisplayDirectory(InitPath)
'setup the dialog to allow multiple files to be selected
oFileDialog.setMultiSelectionMode(True)
'set iAccept as the execution of the dialog
iAccept = oFileDialog.Execute()
'execute and test if dialog works
If iAccept = 1 Then
'set sPath as the chosen file from the dialog
'sPath = oFileDialog.Files(0)
FileArray = oFileDialog.getFiles() 'added by FJCC
'set the function as sPath for returning to the previous sub
fImportLocalFile = FileArray 'modified by FJCC
'end current if statement
End If
End Function
Your error is you are assigning the array of selected files to the funtion name itself! Choose a different name.
This works with me on LO 5.0.0.5
SUB TakeFile()
' Dim FileNames(0 to 100) as String
' Dont limit yourself!
FileNames = fImportLocalFile()
path = FileNames(0)
FOR i = 1 TO Ubound(FileNames)
print path + FileNames(i)
Next
End Sub
and within the function:
path = FileArray(0)
FOR i = 1 TO Ubound(FileArray)
print path + FileArray(i)
Next
fImportLocalFile = FileArray
There is a Interface XFilePicker2 which "extends file picker interface to workaround some design problems." This Interface has a Method getSelectedFiles.
See https://www.openoffice.org/api/docs/common/ref/com/sun/star/ui/dialogs/XFilePicker2.html.
Use this Method instead of XFilePicker.getFiles.
The following should work:
Sub TakeFile()
Dim FileNames() as String
FileNames = fImportLocalFile()
Msgbox Join(FileNames, Chr(10))
End Sub
Function fImportLocalFile() as Variant
Dim oFileDialog as Object
Dim iAccept as Integer
Dim sPath as String
Dim InitPath as String
Dim sFilterNames as String
sFilterNames = "*.csv; *.txt; *.odt; *.ods; *.xls; *.xlt; *.xlsx"
oFileDialog = CreateUnoService("com.sun.star.ui.dialogs.FilePicker")
oFileDialog.AppendFilter("Supported files", sFilterNames)
InitPath = ""
oFileDialog.setDisplayDirectory(InitPath)
oFileDialog.setMultiSelectionMode(True)
iAccept = oFileDialog.Execute()
If iAccept = 1 Then
fImportLocalFile = oFileDialog.getSelectedFiles()
Else
fImportLocalFile = Array()
End If
End Function

Save file path on access field

I'm using access form in which I have a button to explore files and get the path. My form is created to insert data into TABLA1.
TABLA1 contains a field named sPath in which I want to SAVE the files paths.
I reviewd ms access browse for file and get file name and path several times but I don't find solution.
What I'm doing wrong? Why filePath is not saved into sPath field.
I'm using Access 2007. Thank you very much on advance and sorry for I'm limited working with VB.
Private Sub Command7_Click()
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = True
If f.Show Then
For i = 1 To f.SelectedItems.Count
sFile = Filename(f.SelectedItems(i), sPath)
MsgBox sPath & "---" & sFile
Next
End If
End Sub
Public Function Filename(ByVal strPath As String, sPath) As String
sPath = Left(strPath, InStrRev(strPath, "\"))
Filename = Mid(strPath, InStrRev(strPath, "\") + 1)
End Function
Assuming everything else is working, I think you may have to pass your second parameter, sPath, ByRef explicitly. So:
Public Function Filename(ByVal strPath As String, ByRef sPath As String) As String
sPath = Left(strPath, InStrRev(strPath, "\"))
Filename = Mid(strPath, InStrRev(strPath, "\") + 1)
End Function
If you pass it by value, only the value is passed and not the address, so the variable won't reflect updates. Code is assuming sPath is a string - I don't see it declared in your code, though. Look into Option Explicit if that's the case.

MS Access Lotus notes attach multiple files from a folder

I need to figure out how to put a code in MS Access vba for attaching all the files in a selected folder.
Right now I can do just one from a specific location:
PathLocation = "C:\Test\test.PDF"
If Not IsNull(PathLocation) Then
txtAttach = PathLocation
Set objAttachment = objMailDocument.CREATERICHTEXTITEM("strFileAttachment")
Set objEmbedObject = objAttachment.EMBEDOBJECT(1454, "", txtAttach, "strFileAttachment")
End If
But what I really want is to collect all the stuff from the Test folder.
You need the Dir- statement to run through all files in the directory:
Dim PathLocation As String
Dim fileName As String
Dim filePath as String
PathLocation = "C:\Test\"
If Not IsNull(PathLocation) Then
Set objAttachment = objMailDocument.CREATERICHTEXTITEM("strFileAttachment")
fileName = Dir$(PathLocation & "*.*", 0)
Do While fileName <> ""
filePath = PathLocation & fileName
Set objEmbedObject = objAttachment.EMBEDOBJECT(1454, "", filePath, "")
fileName = Dir$()
Loop
End If
To run through e.g. just PDFs replace the *.* in the code above by *.pdf
Hope this should help,there is an example attached at the end as well.
http://bytes.com/topic/access/insights/916710-select-file-folder-using-filedialog-object

Search a folder for keyword

I'm looking to search a folder for a keyword term 'fuel', to pull information from returned files into a 'data' sheet.
For instance, I have a folder week numbers (1 - 52 cross the year so in the new year this will contain one folder but will build as the year goes on).
I search this folder for all .doc files contains the word 'fuel'.
You can do this via a Windows search by typing "fuel" in the search function in the top corner and it will display all filenames and all files that contains the word 'fuel'.
I have this for searching for a file that has 'fuel' in its name, but not inside it.
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("c:\testfolder\")
While (file <> "")
If InStr(file, "fuel") > 0 Then
MsgBox "found " & file
Exit Sub
End If
file = Dir
Wend
End Sub
It isn't particularly pretty, but think something like this should work:
Sub loopThroughFiles()
Dim file As String
file = FindFiles("C:\TestFolder", "fuel")
If (file <> "") Then MsgBox file
End Sub
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Sheell Command And Get Output
Dim files As String
Dim lines
files = CreateObject("Wscript.Shell").Exec("FIND """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
lines = Split(files, vbCrLf)
' Look for matching files
Dim curFile As String
Dim line
For Each line In lines
If (Left(line, 11) = "---------- ") Then
curFile = Mid(line, 12)
End If
If (line = target) Then
FindFiles = curFile
Exit Function
End If
Next
FindFiles = ""
End Function
Uses the FIND command line and then reads the output (hence needing to use Wscript.Shell) and returns first match, or empty string if no file is found
Following #BLUEPIXY's command FINDSTR /M the function can be replaced by:
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Shell Command And Get Output
Dim files As String
files = CreateObject("Wscript.Shell").Exec("FINDSTR /M """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
FindFiles = ""
If (files <> "") Then
Dim idx As Integer
idx = InStr(files, vbCrLf)
FindFiles = Left(files, idx - 1)
End If
End Function

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