MS Access Lotus notes attach multiple files from a folder - vba

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

Related

Find all the PDFs in a folder using Visual Basic in Access

So I am very new with using Visual Basic and I am having trouble. I want to open a folder and read all the PDFs in the folder for content. I found this code on the Microsoft Guidelines, but received errors regarding expectations of certain codes:
For Each foundFile As String In My.Computer.FileSystem.GetFiles(
My.Computer.FileSystem.SpecialDirectories.MyDocuments,
Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.pdf")
Listbox1.Items.Add(foundFile)
Next
Does anyone know why I am getting such errors?
See if this is useful
Sub Dougsloop()
Dim Filename As String
Dim path As String
path = "path to folder" & "\"
Filename = Dir(path & "*.pdf")
Do While Len(Filename) > 0
debug.print; FileName
'Listbox1.Items.AddItem (Filename) replace debug w/this
Filename = Dir
Loop
End Sub

VBA - File Dialog vs Grab Newest File in Directory?

I currently provide a file dialog to permit a user to select the desired file from a pre-defined directory. Works as expected; I am just looking to reduce steps/interaction.
The files are simple timestamped log files, many in the directory. I do not know the actual filename, but I do know the desired file will always be the NEWEST file in that directory.
Is there a way to select the filename for the file with the newest date/time from a known directory?
Thanks!
I found a good approach here:
finding latest file in a folder and opening it (vba access)
Function NewestFile()
Dim FileName As String
Dim MostRecentFile As String
Dim MostRecentDate As Date
Dim FileSpec As String
'Specify the file type, if any
FileSpec = "*.*"
'specify the directory
Directory = "C:"
FileName = Dir(Directory & FileSpec)
If FileName <> "" Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(Directory & FileName)
Do While FileName <> ""
If FileDateTime(Directory & FileName) > MostRecentDate Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(Directory & FileName)
End If
FileName = Dir
Loop
End If
NewestFile = MostRecentFile
End Function
`
A few minor adjustments to suit my needs; works as desired.

VBScript to open a dialog to select a filepath

At present I am opening a file with my vbscript as follows:
strFile = "C:\Users\test\file.txt"
Set objFile = objFSO.OpenTextFile(strFile)
I would like to change this so that a file can be selected/navigated to by the user and that file is used in the script. How can I add this ability? I have tried to search for how to load a file dialog/prompt the user for a file etc just not sure how to complete in a VBScript.
There is another solution I found interesting from MS TechNet less customization but gets what you wanted to achieve. This returns the full path of the selected file.
Set wShell=CreateObject("WScript.Shell")
Set oExec=wShell.Exec("mshta.exe ""about:<input type=file id=FILE><script>FILE.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);</script>""")
sFileSelected = oExec.StdOut.ReadLine
wscript.echo sFileSelected
Here you go:
http://www.robvanderwoude.com/vbstech_ui_fileopen.php
strFile = GetFileName("C:\Users\test\", "Text files|*.txt")
Set objFile = objFSO.OpenTextFile(strFile)
Function GetFileName( myDir, myFilter )
' Written by Rob van der Woude
' http://www.robvanderwoude.com
' Standard housekeeping
Dim objDialog
' Create a dialog object
Set objDialog = CreateObject( "UserAccounts.CommonDialog" )
' Check arguments and use defaults when necessary
If myDir = "" Then
' Default initial folder is "My Documents"
objDialog.InitialDir = CreateObject( "WScript.Shell" ).SpecialFolders( "MyDocuments" )
Else
' Use the specified initial folder
objDialog.InitialDir = myDir
End If
If myFilter = "" Then
' Default file filter is "All files"
objDialog.Filter = "All files|*.*"
Else
' Use the specified file filter
objDialog.Filter = myFilter
End If
' Open the dialog and return the selected file name
If objDialog.ShowOpen Then
GetFileName = objDialog.FileName
Else
GetFileName = ""
End If
End Function
The currently chosen answer doesn't support filters, but hta can be manipulated to support them.
Here's an answer based on this tek-tips.com post (which is also mentioned in
How to add filter to a file chooser in batch?), but I added a full function structure plus support for relative folders:
Function GetFileDlgEx(sIniDir,sFilter)
sTitle = "Choose File"
set objShell = WScript.CreateObject("WScript.Shell")
if instr(sIniDir, ":") <= 0 then
sIniDir = objShell.CurrentDirectory & "\" & sIniDir
end if
sIniDir = Replace(sIniDir,"\","\\")
Set oDlg = objShell.Exec("mshta.exe ""about:<object id=d classid=clsid:3050f4e1-98b5-11cf-bb82-00aa00bdce0b></object><script>moveTo(0,-9999);eval(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(0).Read("&Len(sIniDir)+Len(sFilter)+Len(sTitle)+41&"));function window.onload(){var p=/[^\0]*/;new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(p.exec(d.object.openfiledlg(iniDir,null,filter,title)));close();}</script><hta:application showintaskbar=no />""")
oDlg.StdIn.Write "var iniDir='" & sIniDir & "';var filter='" & sFilter & "';var title='" & sTitle & "';"
GetFileDlgEx = oDlg.StdOut.ReadAll
End Function
sIniDir = "*.*pdf" ' will look in current folder - note extension must be preceded by an asterisk *.
'sIniDir = "docs\*.*pdf" ' will look in a relative folder
'sIniDir = "C:\Windows\*.*pdf" ' will look in an absolute folder
sFilter = "Adobe pdf (*.pdf)|*.pdf|All files (*.*)|*.*|Microsoft Word (*.doc;*.docx)|*.doc;*.docx|Image files (*.gif;*.png;*jpg;*.bmp)|*.gif;*.png;*jpg;*.bmp|Html files (*.htm;*.html;*.mht)|*.htm;*.html;*.mht|"
rep = GetFileDlgEx(sIniDir,sFilter)
MsgBox rep
VBSEdit program installs a COM library VBSEdit Toolkit, which allows Open File dialogs.
From VBSEdit help:
Dialog boxes
OpenFileDialog method
Prompt the user to open a file
toolkit.OpenFileDialog ([initialFolder,[filters,[multiselect,[title]]]])
'Opens a single file
Set toolkit = CreateObject("VbsEdit.Toolkit")
files=toolkit.OpenFileDialog("c:\scripts\","Text Files (*.txt)|*.txt",False,"Open a text file")
If UBound(files)>=0 Then
WScript.Echo files(0)
Else
Wscript.Quit
End If
'Opens multiple files
Set toolkit = CreateObject("VbsEdit.Toolkit")
files=toolkit.OpenFileDialog("c:\scripts\","Text Files (*.txt)|*.txt",True,"Open a text file")
If UBound(files)>=0 Then
For Each filepath In files
WScript.Echo filepath
Next
Else
Wscript.Quit
End If
SaveFileDialog method
Prompt the user to save a file
toolkit.SaveFileDialog ([initialFolder,[initialFilename,[filters,[title]]]])
Set toolkit = CreateObject("VbsEdit.Toolkit")
filepath = toolkit.SaveFileDialog("c:\scripts","test.txt","Text Files (*.txt)|*.txt")
If Not(IsNull(filepath)) Then
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(filepath,True)
objFile.WriteLine Date
objFile.Close
Else
Wscript.Quit
End If
SelectFolder method
Prompt the user to select a folder
toolkit.SelectFolder ([initialDir,[title]])
Set toolkit = CreateObject("VbsEdit.Toolkit")
myfolder=toolkit.SelectFolder("c:\scripts\","Please select a folder")
If Not(IsNull(myfolder)) Then
WScript.Echo myfolder
Else
Wscript.Quit
End If
…
(Actually, folder selection dialogs can be opened without VBSEdit toolkit, with BrowseForFolder method of Shell.Application object.)
Found this answer HERE
Set WshShell=CreateObject("Wscript.Shell")
WshShell.BrowseForFolder(0, "Please select the folder.", 1, "")

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

Dir Function in Excel 2010 VBA not working

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