Question on FileOpen Dialog

  • Thread starter Montana DOJ Help Desk
  • Start date
M

Montana DOJ Help Desk

Word 2000

I have the following code.

If Err.Number = 52 Then
With Dialogs(wdDialogFileOpen)
.Name = "Error.log"
.Display
End With
End if

Error 52 is a bad file name or file number. This is part of an error
handling routine. Basically, if the path to the error log does not exist,
then the user is given the opportunity to specify the path to the error log.
The problem is that if the folder selected by the user is empty, the Open
button in the dialog box will not work. Is there a way around this?

-- Tom

State of Montana
Department of Justice Help Desk

"Making the world a safer place."
 
J

Jean-Guy Marcil

Bonjour,

Dans son message, < Montana DOJ Help Desk > écrivait :
In this message said:
Word 2000

I have the following code.

If Err.Number = 52 Then
With Dialogs(wdDialogFileOpen)
.Name = "Error.log"
.Display
End With
End if

Error 52 is a bad file name or file number. This is part of an error
handling routine. Basically, if the path to the error log does not exist,
then the user is given the opportunity to specify the path to the error log.
The problem is that if the folder selected by the user is empty, the Open
button in the dialog box will not work. Is there a way around this?

Try this instead:

'_______________________________________
Sub SelectFolder()
'Needs a reference to (Tools > Reference)
'Microsoft Shell Controls And Automation
'Simple version

Dim oShell As Shell32.Shell
Dim oFolder As Shell32.Folder
Dim EverythingOK As Boolean

EverythingOK = False

Set oShell = New Shell32.Shell
Set oFolder = oShell.BrowseForFolder(0, "Select ", 0)

On Error GoTo NoPath
MsgBox oFolder.Self.Path
EverythingOK = True

NoPath:
Set oFolder = Nothing
Set oShell = Nothing

If EverythingOK Then Exit Sub

On Error GoTo 0
MsgBox "Action cancelled by user.", vbExclamation, "Cancelled"

End Sub
'_______________________________________

'_______________________________________
Function GetFolderName(sCaption As String) As String
Dim oShell As Shell32.Shell
Dim oFolder As Shell32.Folder
Dim oItems As Shell32.FolderItems
Dim Item As Shell32.FolderItem

On Error GoTo CleanUp

Set oShell = New Shell ' ActiveX interface to shell32.dll
Set oFolder = oShell.BrowseForFolder(0, sCaption, 0)
Set oItems = oFolder.Items
Set Item = oItems.Item

GetFolderName = Item.Path

CleanUp:
Set oShell = Nothing
Set oFolder = Nothing
Set oItems = Nothing
Set Item = Nothing

End Function
'_______________________________________

Or:

'_______________________________________
Const BIF_RETURNONLYFSDIRS = 1
Const BIF_NEWDIALOGSTYLE = &H40
Const MAX_PATH = 260

Type BROWSEINFO
hWndOwner As Long
pidlRoot As Long
pszDisplayName As Long
lpszTitle As String
ulFlags As Long
lpfn As Long
lparam As Long
iImage As Integer
End Type

Declare Function GetActiveWindow Lib "user32" () As Long
Declare Function SHBrowseForFolder Lib "Shell32" _
(pBrInfo As BROWSEINFO) As Long
Declare Function SHGetPathFromIDList Lib "Shell32" _
(ByVal pidList As Long, _
ByVal lpBuffer As String) As Long
Declare Sub CoTaskMemFree Lib "ole32.dll" _
(ByVal pMem As Long)

Option Explicit
'sTitle = text inside browse for folder box
'_______________________________________
Public Function SelectFolder(sTitle) As String
Dim nPos As Long
Dim pidList As Long
Dim nResult As Long
Dim sPath As String
Dim pBInfo As BROWSEINFO

sPath = String(MAX_PATH, Chr(0))
sTitle = sTitle & Chr(0)

With pBInfo
'Set the owner window (current active Window)
.hWndOwner = GetActiveWindow()
.lpszTitle = sTitle

' BIF_NEWDIALOGSTYLE let the user resize the Window
' and also create new folders, delete folders and some more.
' If that is not desired, use only BIF_RETURNONLYFSDIRS

.ulFlags = BIF_RETURNONLYFSDIRS + BIF_NEWDIALOGSTYLE
' .ulFlags = BIF_RETURNONLYFSDIRS
End With

pidList = SHBrowseForFolder(pBInfo)

If pidList <> 0 Then
SHGetPathFromIDList pidList, sPath
CoTaskMemFree pidList
nPos = InStr(sPath, Chr(0))
If nPos > 0 Then
sPath = Left(sPath, nPos - 1)
End If
End If

SelectFolder = sPath

End Function
'_______________________________________

'_______________________________________
Sub Folder_API()
Dim Mypath As String

Mypath = SelectFolder("Choose a folder")

If Replace(Mypath, Chr(0), "") = "" Then
MsgBox "No folder was chosen, or action was cancelled.", _
vbExclamation, "No folder"
Exit Sub
End If

MsgBox Mypath

End Sub
'Lars-Eric Gisslén
'_______________________________________

--
Salut!
_______________________________________
Jean-Guy Marcil - Word MVP
(e-mail address removed)
Word MVP site: http://www.word.mvps.org
 
M

Montana DOJ Help Desk

Thanks for the reply and information!

I tried your first method, and it was causing repeated critical errors with
Windows Explorer (Kept getting the "Send Error Report" message). I made
sure to set the reference to Microsoft Shell Controls And Automation, so I'm
not sure what the problem was with this approach.

Your second method worked perfectly.

After getting your second method working, I began to think that there was a
better way to structure my subroutine. I figured that by making checks for
the appropriate folder and file before opening the file for appending, I
could probably avoid the need for an error handler altogether (in this
specific routine). So I re-wrote most of my subroutine, and this is what it
looks like now.

***************
Sub ErrorLogging()

Dim ErrDateTime As Date
Dim ErrorLog As String
Dim FileNumber As Long
Dim FSO As Object
Dim NewFile As Object

' Sets the error date and time, builds the name of the error log file,
creates
' a file system object, and then checks for the existence of the error log
and
' creates one if necessary.
ErrDateTime = FormatDateTime(Now, vbGeneralDate)
ErrorLog = ActiveDocument.Path & "\Error.log"
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(ErrorLog) = False Then Set NewFile =
FSO.CreateTextFile(ErrorLog)

' Gets the next avaiable file number and opens the error log for appending.
FileNumber = FreeFile
Open ErrorLog For Append As FileNumber

' Writes comma-delimited data to Error.log, and then inserts a blank line
into the file.
Write #FileNumber, ErrDateTime, ModuleName, Subroutine, Err.Number,
Err.HelpContext, Err.Description, Err.HelpFile, cbDataClip
Write #FileNumber,

' Closes the file and exits the routine.
Close #FileNumber

End Sub
***************

Any constructive feedback on the above routine would be welcomed. As far as
I can see, the error log should always be either found to already exist, or
successfully created. Therefore, it should always be successfully opened
and written to, so I can't really see a need for an error handler in this
routine. Can anyone spot a reason why this wouldn't be true?

ModuleName, Subroutine, and cbDataClip are declared at the module level
because they are set in other subroutines, and passed to this one.
ModuleName and Subroutine are set so that a programmer looking at the error
log will know which module and subroutine were active when the error was
encountered. The cbDataClip value is the data that was being processed when
the error occurred.

I was a little concerned about the following line of code:

ErrorLog = ActiveDocument.Path & "\Error.log"

I thought that if the active document somehow got changed while the macros
are running (i.e. The user switches to another document while a dialog box
is displayed) then the error log could end up in the wrong folder. But I
tried to trip up the code by stepping through it and switching documents in
the process, and each time the error log was created in the correct folder
(The correct folder being the folder containing the document that the macros
are in). Can anyone foresee an instance where the error log would NOT end
up the correct folder?

-- Tom

State of Montana
Department of Justice Help Desk

"Making the world a safer place."
 
M

Montana DOJ Help Desk

Okay, I found an error with my new code. If the error log does not exist,
then it is created with the following command:

If FSO.FileExists(ErrorLog) = False Then Set NewFile =
FSO.CreateTextFile(ErrorLog)

However, when a new file is created, then the following command causes an
error:

Open ErrorLog For Append As FileNumber

The error only occurs when the code creates the file. Otherwise, it works
fine. I guess I could trap the error and make it work, but I'm going to
work on changing the code so that the error doesn't occur in the first
place.

-- Tom

State of Montana
Department of Justice Help Desk

"Making the world a safer place."
 
P

Peter_A_M (NL)

Hello,
Although I've seen that your question has been answered already, I'd like to
suggest another direction as a possible solution (but it's no way a complete
one).

I've been using in the past (Excel) Application.GetOpenFileName. But it
didn't exist in Word.
Since recently in Office there is even a more sophisticated solution, i.e.
the socalled 'folder picker', e.g.:
Dim fd As FileDialog
Set fd = FileDialog(msoFileDialogFolderPicker)
(other constants available).
With fd
If .Show = -1 Then
MsgBox .SelectedFiles(1) 'shows path of selected folder when
clicking Open
...
'determine if file exists (MyFile results either in "Error.Log" or
in "")
MyFile = Dir(.SelectedFiles(1) + "Error.Log")
...
Else
...
End
End With

What do you think of this?
Greets,
Peter
 
M

Montana DOJ Help Desk

I get a "User-defined type not defined" compile error with your code. Do I
have to set a reference or something?

-- Tom

State of Montana
Department of Justice Help Desk

"Making the world a safer place."
 
P

Peter_A_M (NL)

You're right - I'm so sorry - I was a bit careless.

- FileDialog should read: Application.FileDialog
- SelectedFiles should read: SelectedItems (twice)
- End (after Else) should read (ofcourse): End If

This should work, at least it did with me!
Lesson learned: always test what you write down.

Kind regards,
Peter

PS:
search Help on FileDialog and Properties/Methods; e.g. you could add (after
"With fd" but before ".Show"):
.Title = "Select folder in which Error.log belongs"
 
P

Peter_A_M (NL)

It's awful - yet another fault:
The sentence with MyFile should contain Application.PathSeparator.

Well, now completely anew:

Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
'(other constants available)
With fd
.Title = "Select folder in which Error.log belongs"
If .Show = -1 Then
MsgBox .SelectedItems(1) 'shows path of selected folder when
clicking Open
'...
'determine if file exists (MyFile results either in "Error.Log" or
in "")
MyFile = Dir(.SelectedItems(1) + Application.PathSeparator +
"Error.Log")
MsgBox MyFile
'...
Else
'...
End If
End With


Greets again,
Peter
 
M

Montana DOJ Help Desk

No problem. Honestly, I got the compile error and couldn't get past that
point, so I didn't really look at the rest of the code. In fact, I still
get "User-defined type not defined" compile error when I try to run the
code. I figure that the problem is caused by not having the correct
reference set. If I type:

dim fd as

"FileDialog" does not appear on the list of choices. I did a little
research and it sounds like I need to set a reference to the Microsoft
Office 10.0 Object Library, but I only have the 9.0 object library. I'm
using Word 2000, and I wonder if the 10.0 object library is only available
in later versions of Word.

-- Tom

State of Montana
Department of Justice Help Desk

"Making the world a safer place."
 
J

Jonathan West

Montana DOJ Help Desk said:
No problem. Honestly, I got the compile error and couldn't get past that
point, so I didn't really look at the rest of the code. In fact, I still
get "User-defined type not defined" compile error when I try to run the
code. I figure that the problem is caused by not having the correct
reference set. If I type:

dim fd as

"FileDialog" does not appear on the list of choices. I did a little
research and it sounds like I need to set a reference to the Microsoft
Office 10.0 Object Library, but I only have the 9.0 object library. I'm
using Word 2000, and I wonder if the 10.0 object library is only available
in later versions of Word.

Correct.

The FileDialog was introduced in Office XP or 2003 (I can't offhand remember
which)

If you want to use a File Open dialog in Word 2000, you need to use the
Dialogs collection. This article contains a code sample that demonstrates
using the File Open dialog

Useful WordBasic commands that have no VBA equivalent
http://word.mvps.org/FAQs/MacrosVBA/WordBasicCommands.htm

Take a look at the section titled FileNeameInfo$()
 
M

Montana DOJ Help Desk

Okay, that's what I suspected. I've worked with the File Open dialog in
Word 2000 by using the Dialogs collection, so I'm familiar with that. I
just wanted to review Peter's solution to see if I could make use of it.
Unfortunately, I don't have the option at work of upgrading to Office XP or
2003, but I do use Office XP at home, so I'll check it out there. Thanks
for the info.

-- Tom

State of Montana
Department of Justice Help Desk

"Making the world a safer place."
 

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