PDA

View Full Version : application.filedialog help



red102
08-08-2014, 03:35 AM
Hi,

The below code copies the contents of some fields in one word document over to corresponding fields in another, but it is reliant on the source form having a static name, and both files being in the same directory. What I would like to achieve is being able to have the destination document in any directory and when run, the code opens a explorer window allowing me to navigate to, and open my source document irrelevant of what it is called.
I’ve been experimenting with application.filedialog(msofiledialogopen) with little success….and much frustration. If this is not the best way to go, I'm open to suggestions.
Any help or guidance would be greatly appreciated. You can probably tell form the structure of my code and the question that I’m asking, that I’m only just starting with VBA :cloud9:


Sub CopyFields()


'when the log changes this has to be edited...
Dim logName As String
logName = "LOG_1.doc" ' <--------------

'defines nice names for the two documents...
Dim LogFile As Word.Document
Dim ThisREPORTFile As Word.Document

Dim filePath As String
Dim REPORTName As String
Set ThisREPORTFile = ActiveDocument
filePath = ThisREPORTFile.Path 'assumes log in same directory as report
REPORTName = ThisREPORTFile.Name


'sets up these definitions for convenience...
Dim oREPORTFields As FormFields
Dim oLogFields As FormFields
Set oREPORTFields = ThisREPORTFile.FormFields
Set oLogFields = LogFile.FormFields

'copies fields
oREPORTFields("ReportFiled1").Result = oLogFields("logFiled1").Result
oREPORTFields("ReportFiled2").Result = oLogFields("logFiled2").Result
oREPORTFields("ReportFiled3").Result = oLogFields("logFiled3").Result
oREPORTFields("ReportFiled4").Result = oLogFields("logFiled4").Result

End Sub

gmayor
08-10-2014, 03:24 AM
Call a simple function from your macro to get the filename in question e.g.


Dim strFileName As String
strFileName = BrowseForFile("Select the required document")
If strFileName = vbNullString Then
MsgBox "User Cancelled"
Exit Sub
End If
'Do stuff with strfilename e.g.
MsgBox strFileName


The Function in question is as follows, which you can use any time you need to get a filename and path from the filing system


Function BrowseForFile(Optional strTitle As String) As String
Dim fDialog As FileDialog
On Error GoTo Err_Handler
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.Title = strTitle
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Word documents", "*.doc,*.docx,*.docm"
.InitialView = msoFileDialogViewList
If .Show <> -1 Then GoTo Err_Handler:
BrowseForFile = fDialog.SelectedItems.Item(1)
End With
lbl_Exit:
Exit Function
Err_Handler:
BrowseForFile = vbNullString
Resume lbl_Exit
End Function