is my code correct?

epicmove

Ben
Local time
Today, 19:13
Joined
Apr 21, 2006
Messages
59
Hi guys,

Just want to check to see if a text file exists. If it does, then open it. If it doesnt, display a message.
Have written the following code. Wondered how I can use the FileSystemObject to actually open the text file rather than using the Application.FollowHyperlink.
Still learning VBA so just want to make sure that I am coding efficiently.

Code:
Private Sub CmdIPConfig_Click()
On Error GoTo Err_CmdIPConfig_Click

    Dim fso As Object
    Dim stFileName As String
    
    stFileName = "\\ServerName\Directory\SubDirectory" & Me!Parent!Equipment_Identifier & ".txt"
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    If fso.FileExists(stFileName) Then
        Application.FollowHyperlink (stFileName) 'if text file exists then open it
    Else
        MsgBox "IP Config File Does Not Exisit", vbOKOnly, "Error: Unable To Locate File" 'else text file does not exist. display message to a user
    End If
        
Exit_CmdIPConfig_Click:
    Exit Sub
Err_CmdIPConfig_Click:
    MsgBox Err.Description
    Resume Exit_CmdIPConfig_Click:
End Sub

Note: I have just hacked the code out of other modules I have found by searching. Open to any better suggestions.

Thanks
BF
 
ShellExecute API

Code looks fine to me.
My understanding of the FileSystemObject is that it offers methods and properties for file system management, not launching applications.
I've used the FollowHyperlink approach in a project I'm working on, but I'm looking into the ShellExecute API, which seems to offer significant advantages, notably that hyperlinks choke on the "#" character and my users love using "#" in filenames.

Code:
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hwnd As Long, _
  ByVal lpOperation As String, _
  ByVal lpFile As String, _
  ByVal lpParameters As String, _
  ByVal lpDirectory As String, _
  ByVal nShowCmd As Long _
  ) As Long

Sub Testing()
   Launch "C:\", "TestFile.doc"
End Sub

Sub LaunchFileApp(sPath As String, sFile As String)
   Dim lResult As Long
[COLOR="Green"]   'leverages the "&Open" verb of the file, 
   'launching the application associated in Windows
   'with the type of the specified file, sFile
[/COLOR]   lResult = ShellExecute(0, "Open", sFile, "", sPath, 1)
   If lResult Then MsgBox "Launch failure"
End Sub

Type "ShellExecute" into a seach box at www.microsoft.com for lots more info.
 

Users who are viewing this thread

Back
Top Bottom