Searching and opening a file with a certain extension

J

Jason Logue

With a template open, I need to open another file and
insert it, and that specific file always has the same
extension, but the name varies.


What is the code for automating the ability of Word to
open a specific folder on a network and retrieving a file
with a specific extenstion (e.g, txt, doc)?


TIA,
Jason
 
D

Dave Lett

Hi Jason,

You can modify the routine from the article "How to read the filenames of
all the files in a directory into an array" at
http://www.mvps.org/word/FAQs/MacrosVBA/ReadFilesIntoArray.htm, as in the
following (just be sure that the you file that you want to insert is the
only file with that extension in the folder you specify):

Dim MyFile As String
Dim Counter As Long
Dim sDir As String

'Create a dynamic array variable, and then declare its initial size
Dim DirectoryListArray() As String
ReDim DirectoryListArray(1000)
' set the folder where the file is located
sDir = "c:\temp\"

'Loop through all the files in the directory by using Dir$ function
'for your purposes, this file should be the only one with that extension
'in the folder (notice the "*.doc", which sets the extension you're looking
for)
MyFile = Dir$(sDir & "*.doc")
Do While MyFile <> ""
DirectoryListArray(Counter) = MyFile
MyFile = Dir$
Counter = Counter + 1
Loop

'Reset the size of the array without losing its values by using Redim
Preserve
ReDim Preserve DirectoryListArray(Counter - 1)

For Counter = 0 To UBound(DirectoryListArray)
Selection.InsertFile FileName:=sDir & DirectoryListArray(Counter)
Next Counter

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top