# Solved: Word macro File Open ...Filename



## Ziggy1 (Jun 18, 2002)

I am stumped, I can do this in Excel, but it is not the same in Word, the code below works as far as brinig up the file open in the Directory that I want, but I can't figure out how to grab the selected filename and assign it to a variable


' Set the default directory.
' Note: Substitute any existing directory.
Options.DefaultFilePath(Path:=wdDocumentsPath) = "\\10.3.16.243\9105_boh"

Dim MyDialog As Dialog
Set MyDialog = Dialogs(wdDialogFileOpen)
MyDialog.Name = "*.txt"
MyDialog.Show


The remainder of the code would be

Documents.Open FileName:="MyFile.txt", ConfirmConversions:=False, ReadOnly:= _
' False, AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:= _
' "", Revert:=False, WritePasswordDocument:="", WritePasswordTemplate:="", _
' Format:=wdOpenFormatAuto


rest does not matter, but I would guess I need the MyFile.txt to be replaced by the variable, I could not find any good forums on Word VBA

thanks


----------



## Ziggy1 (Jun 18, 2002)

FYI in Excel I use.....

Dim FileToOpen As Variant
'

FileToOpen = Application _
.GetOpenFilename("Text Files (*.txt), *.txt")
If FileToOpen <> False Then
End If

Workbooks.OpenText FileToOpen, Origin:=xlWindows _
, StartRow:=1, DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, _
2), Array(11, 1), Array(21, 1), Array(31, 1), Array(41, 1),


----------



## Ziggy1 (Jun 18, 2002)

well I found this, which is getting me closer. It works but it keeps erroring out, but if I click continue it works!!!! Arrrggghhhhhhh help!!!

Dim FileToOpen As String

' Set the default directory.
' Note: Substitute any existing directory.
Options.DefaultFilePath(Path:=wdDocumentsPath) = "\\10.3.16.243\9105_boh"

With Dialogs(wdDialogFileOpen)
If .Display <> 0 Then
FileToOpen = WordBasic.FilenameInfo(.Name, 1)
Else
MsgBox "No file selected"
End If
End With


----------



## bomb #21 (Jul 1, 2005)

Is it possible to do a SendKeys (Enter) (as one can in Excel, altho' *not* recommended) at the "hurdle"?


----------



## Ziggy1 (Jun 18, 2002)

Not sure Bomb, anyways I did a restart and the debug error went away and the code is working. anyone interested might want to take note because I had a hell of a time finding info...but maybe it's just me.....here is the beginng of the code, if you were to record a macro to find a specific file, you could then edit it to use this code to let you choose the file (from a specific directory). I needed it to default to the directory also because this is a server location that is difficult to navigate to.

Sub Reports()
'
' Reports Macro
' Macro recorded 9/26/06 by ziggy
'

Dim FileToOpen As String

' Set the default directory.
' Note: Substitute any existing directory.
Options.DefaultFilePath(Path:=wdDocumentsPath) = "\\10.3.16.243\9105_boh"

With Dialogs(wdDialogFileOpen)
On Error Resume Next
If .Display <> 0 Then
FileToOpen = WordBasic.FilenameInfo(.Name, 1)
Else
MsgBox "No file selected"
End If
End With

Documents.Open FileName:=FileToOpen, ConfirmConversions:=False, ReadOnly:= _
False, AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:= _
"", Revert:=False, WritePasswordDocument:="", WritePasswordTemplate:="", _
Format:=wdOpenFormatAuto
Selection.WholeStory
Selection.Font.Size = 8
With ActiveDocument.PageSetup
.LineNumbering.Active = False
.Orientation = wdOrientLandscape
.TopMargin = InchesToPoints(0.92)

.....the rest of your code

End Sub


----------



## Ziggy1 (Jun 18, 2002)

FYi if anyone wants it.... here is the full working code, I made more changes,

The code will alter your Default the File Open Location to a specific location (coded), but it resets back at the end of the code. It allows me to grab files quickly that are saved in a difficult location (Read Only) by our main system, format the Page and then Save to the users folder where they can work with it

It separates the filename from the Path so I can use it in the Save path

The original code I found here, but I have tweaked it to suit my needs...

'Macro recorded/Edited 9/26/06 by ziggy

Sub FileOpenTest()

Dim FileToOpen
Dim FileToSave

Dim szFileName As String
Dim wrdDoc As Document
'''This is just demonstrate the below library function.
szFileName = FileOpenCustom1("", "*.Doc;*.txt")

'''In reality it would be more productive to pass a document object back.
If szFileName <> "" Then
Set wrdDoc = Word.Documents(szFileName)

' disabled
' MsgBox wrdDoc.Path + Chr$(13) + wrdDoc.Name

FileToOpen = wrdDoc.Name

'Modified Ziggy sept 29 2006
'Parse out .txt and replace with .doc
FileToSave = Left(wrdDoc.Name, Len(wrdDoc.Name) - 4) & ".doc"

Dim varDocOne As Variant

Documents.Open FileName:=FileToOpen, ConfirmConversions:=False, ReadOnly:= _
False, AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:= _
"", Revert:=False, WritePasswordDocument:="", WritePasswordTemplate:="", _
Format:=wdOpenFormatAuto
Selection.WholeStory
Selection.Font.Size = 8
With ActiveDocument.PageSetup
.LineNumbering.Active = False
.Orientation = wdOrientLandscape
.TopMargin = InchesToPoints(0.92)
.BottomMargin = InchesToPoints(0.92)
.LeftMargin = InchesToPoints(1)
.RightMargin = InchesToPoints(1)
.Gutter = InchesToPoints(0)
.HeaderDistance = InchesToPoints(0.5)
.FooterDistance = InchesToPoints(0.5)
.PageWidth = InchesToPoints(11)
.PageHeight = InchesToPoints(8.5)
.FirstPageTray = wdPrinterDefaultBin
.OtherPagesTray = wdPrinterDefaultBin
.SectionStart = wdSectionNewPage
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.VerticalAlignment = wdAlignVerticalTop
.SuppressEndnotes = False
.MirrorMargins = False
.TwoPagesOnOne = False
.GutterPos = wdGutterPosLeft
End With
ChangeFileOpenDirectory _
"C:\Reports" ' Make Sure directory exists
ActiveDocument.SaveAs FileName:=FileToSave, FileFormat:=wdFormatDocument, _
LockComments:=False, Password:="", AddToRecentFiles:=True, WritePassword _
:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False
MsgBox "File " & FileToSave & " Saved to:" & vbNewLine & vbNewLine & " C:\Reports"

ActiveDocument.Close

End If
End Sub
'''
''' Function: FileOpenCustom
'''
''' Comments: Returns the document name if successful. Path of
''' document should be obtained from the document via
''' FileNameFromWindow$() minus the return value.
'''
''' Arguments: pszInitDir$ initial directory.
''' pszFilter$ initial filters to use in dialog.
'''
''' Returns: Filename for success, empty string for failure.
'''
''' Date Developer Action
''' ------------------------------------------------------------------
''' 6/07/96 Steven (Smitch) Mitchell Created
''' Copyright Baarns Consulting Group, Inc. 1996
'''
Function FileOpenCustom1(pszInitDir As String, pszFilter As String) As String
Dim dlgFileOpen As Word.Dialog
Dim szCurDir As String
Dim szdlgFullName As String
Dim wrdDoc As Word.Document

'''Store the current document path
szCurDir = Application.Options.DefaultFilePath(wdDocumentsPath)
'''If pszInitDir is empty use the default path.

' Set the default directory. 'Modified Ziggy sept 29 2006
' Note: Substitute any existing directory.
Options.DefaultFilePath(Path:=wdDocumentsPath) = "\\ServerTest"

If pszInitDir <> "" Then
ChDir pszInitDir
Else
pszInitDir = szCurDir
End If
'''Initailize and reference the dialog object.
Set dlgFileOpen = Word.Dialogs(wdDialogFileOpen)
With dlgFileOpen
'''Update the dialog object.
.Update

'''Set the filter
.Name = pszFilter
'''Display and execute the dialog.
If .Show() <> False Then
'''If the user didn't cancel...
'''The active document is the one just opened.
Set wrdDoc = ActiveDocument
'''Cheat and use the document object to do the parsing.
'''Return the name of the document.
FileOpenCustom1 = wrdDoc.Name

End If
End With

'''Restore the default path setting.
With Application.Options
If .DefaultFilePath(wdDocumentsPath) <> szCurDir Then
.DefaultFilePath(wdDocumentsPath) = szCurDir
End If
End With
End Function


----------

