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.
Related
So here's the scenario. Everyday, there is a Zip file created called "Bundle_06112018063917" (The numbers are the date and time at which the zip is created, therefore they change everyday).
The code below extracts all the files into a separate folder beautifully!
Sub UnzipAFile(zippedFileFullName As Variant, unzipToPath As Variant)
Dim ShellApp As Object
'Copy the files & folders from the zip into a folder
Set ShellApp = CreateObject("Shell.Application")
ShellApp.Namespace(unzipToPath).CopyHere
ShellApp.Namespace(zippedFileFullName).items
End Sub
Sub Dump()
Call UnzipAFile("G:\DP\Mstanley\history\JUN18\WESTROCK\Bundle_06112018063917.zip", _
"G:\DP\Mstanley\history\JUN18\WESTROCK\Dump")
End Sub
The Problem:
The name of the zip file changes everyday based on the date and time in which the zip is created. Therefore I need a way to refer to zip file with just "Bundle_".
Below is what I tried, but still no luck.
Sub doingstuff()
Dim pSTR As String
Dim strFile As String
Dim WB As Workbook
Dim dirFile As String
pSTR = "G:\DP\Mstanley\history\JUN18\WESTROCK\"
strFile = "Bundle_" & "*" & ".zip"
dirFile = Dir(pSTR & strFile)
Call UnzipAFile(dirFile, "G:\DP\Mstanley\history\JUN18\WESTROCK\Dump")
End Sub
Any ideas/help would be much appreciated!
You need to loop through all the files and do whatever you want to the files that you want to handle.
When you're done, move the file to an archive folder.
Dim di As DirectoryInfo = New DirectoryInfo("C:\ExampleDir\")
For Each fi In di.GetFiles()
' Unzip file file
' do stuff to the contents
' move the file to an archive folder
Next
I changed the signature of your UnzipAFile sub. Do you really want to accept any variable type or do you want strings?
This will search a folder for the latest "Bundles_" file and unzip that one. I couldn't make sense of the "date" at the end of the bundles files so I'm using the Date Modified on the zip file itself.
This solution required a reference to Microsoft Scripting Runtime (the scrrun.dll file)
Sub UnzipLatest(bundlesFolder As String, unzipToPath As String)
Dim fil As File, fol As Folder
Dim fso As New FileSystemObject
Dim latestDate As Date, latestFile As String, latestBundleFileFound As Boolean
If Not fso.FolderExists(bundlesFolder) Then Exit Sub
Set fol = fso.GetFolder(bundlesFolder)
For Each fil In fol.Files
If fil.Name Like "*Bundles_*" Then
latestBundleFileFound = True
If fil.DateLastModified > latestDate Then
latestDate = fil.DateLastModified
latestFile = fil.path
End If
End If
Next
If latestBundleFileFound Then
UnzipAFile latestFile, unzipToPath
End If
End Sub
Sub UnzipAFile(zippedFileFullName As String, unzipToPath As String)
End Sub
I'm trying to pull text from a bunch of XML files into Word. I'm working from a list of files and have found that some of them don't actually exist in the folder. So, I'm using this function to check whether the files actually exist before opening them. But I'm still getting error 52 (Bad file name or number).
This is the function:
Function FileThere(FileName As String) As Boolean
FileThere = (Dir(FileName) > "")
End Function
And this is the code I'm calling it from:
Sub PullContent()
Dim docList As Document
Dim docCombinedFile As Document
Dim objFileListTable As Table
Dim objRow As Row
Dim strContent As String
Dim strFileCode As String
'Code # for the current file. (Pulled in temporarily, output to the Word doc.)
Dim strFilename As String
'Name of XML file. Created based on strFileCode
Set docCombinedFile = Documents.Add
'The new doc which will list all warnings
Dim strXml As String
'String variable that holds the entire content of the data module
Dim strInvalidCodes
'String listing any invalid file codes. Displayed at the end.
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Documents.Open FileName:="C:\Users\kelly.keck\Documents\Triton MTS\IETMs - Test\IETMList.docx"
Set docList = Documents("IETMList.docx")
Set objFileListTable = docList.Tables(1)
For Each objRow In objFileListTable.Rows
strFileCode = objRow.Cells(4).Range.Text
strFileCode = Left(strFileCode, Len(strFileCode) - 2)
strFilename = strFileCode & ".xml"
strPath = "C:\Applications\xml\"
If FileThere(strPath & strFileCode) = True Then
'MsgBox (strPath & strFilename)
strXml = FSO.OpenTextFile(strPath & strFilename).ReadAll
Else
strInvalidCodes = strInvalidCodes & vbCr & strFileCode
End If
Next
MsgBox ("The following filenames were invalid: " & vbCr & strInvalidCodes)
End Sub
Getting this error seems to defeat the purpose of having a function to check if a file exists, but I'm not sure what's wrong with the function.
A bit late to the party, but this hasn't had an accepted answer yet.
I generally use this method to test if a file exists, and your code uses FileSystemObject already so could use that reference.
Public Function FileExists(ByVal FileName As String) As Boolean
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
FileExists = oFSO.FileExists(FileName)
End Function
I believe that you need to be sure that FileThere is actually returning the Boolean value you intend. It would be more reliable if you checked the Len property (the number of characters) or checked whether it actually returns the empty string.
The following is more verbose than absolutely necessary in order to make the logic clear. If you were to use Len, instead, then you'd check Len(Dir(FileName)) > 0
Function FileThere(FileName as String) as Boolean
Dim bFileExists as Boolean
If Dir(FileName) = "" Then
bFileExists = False
Else
bFileExists = True
End If
FileThere = bFileExists
End Function
1st module..
Public Sub Directory_Path()
Dim Directory As String
Directory = InputBox("Enter the Directory path that contains folders ""This Quarter"",""Last Quarter"",""Second_Last_Quarter"".")
If Right(Directory, 1) = "\" Then
Directory = Left(Directory, Len(Directory) - 1)
End If
End Sub
I called the the first module in 2nd module using Public Sub Directory_Path() . I want Directory variable in first module to be used as a variable in 2nd module... Help me. I miss something... If this question is repeated, please answer me and I will delete this post.
The most obvious solution is to just make it a function...
Public Function Directory_Path() As sting
Dim Directory As String
Directory = InputBox("Enter the Directory path that contains folders " & _
"""This Quarter"",""Last Quarter"",""Second_Last_Quarter"".")
If Right(Directory, 1) = "\" Then
Directory_Path = Left(Directory, Len(Directory) - 1)
Else
Directory_Path = vbNullString
End If
End Function
...and then call the function:
Debug.Print Directory_Path
Note that instead of requiring the user to type the path, you can use the FileDialog instead:
Public Function Directory_Path() As String
Dim prompt As FileDialog
Set prompt = Application.FileDialog(msoFileDialogFolderPicker)
With prompt
.Title = "Select Directory path that contains folders " & _
"""This Quarter"",""Last Quarter"",""Second_Last_Quarter""."
.AllowMultiSelect = False
If .Show <> 0 Then Directory_Path = .SelectedItems(1)
End With
End Function
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
I am trying to loop through a given directory to find the latest downloaded csv file. For some reason my Dir function won't find any file even if the file does exist. I am not totally familiar with VBA so i may perhaps be missing some sort of reference to perform the Dir function, but I can't find anything online that tells me I need to. All the examples and forums use Dir just like I do, but I can't get mine to work. Here is the code, please tell me if you can see what I am doing wrong:
Public Function Get_File() as string
Dim filePath As String
ChDir ("..")
filePath = CurDir
'Goes back to Documents directory to be in same directory as macro
ChDir (filePath & "\Documents")
filePath = filePath & "\Downloads\test.txt"
filePath = getLatestFile(filePath)
Get_File = filePath
End Function
Public Function getLatestFile(pathToFile As String) As String
Dim StrFile As String
Dim lastMod As Variant
Dim nextMod As Variant
Dim lastFileName As String
StrFile = Dir(pathToFile)
lastFileName = StrFile
lastMod = FileDateTime(StrFile)
While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
nextMod = FileDateTime(StrFile)
If nextMod > lastMod Then
lastFileName = StrFile
lastMod = nextMod
End If
Wend
getLatestFile = lastFileName
End Function
The test.txt file is in my Downloads file and the filePath string prints out to be the correct path, but I keep getting an error stating that it can't find the file. It fails at the first use of Dir(pathToFile). Any help would be greatly appreciated.
Dir() only returns the filename portion of the path, i.e., it does not return the folder portion. For example,
Dir("C:\MyPath\MyFile.txt")
returns MyFile.txt not C:\MyPath\MyFile.txt