Ermitteln, ob eine Datei vorhanden ist in Excel-VBA
Visual Basic für Applikationen (VBA) ist eine Teilmenge von Visual Basic, mit dem Microsoft Office-Programme an Ihre Bedürfnisse anpassen. Beim Schreiben in eine Datei im VBA ist es empfehlenswert, stellen Sie sicher, dass diese Datei vorhanden ist, bevor Sie versuchen zu schreiben. Wenn Sie möchten finden, wenn Excel eine Datei vorhanden ist, erstellen Sie ein VBA-Modul, das der Trick funktioniert. Um diese Funktion nutzen zu können, sollten Sie einige frühere Erfahrungen mit VB-Programmierung haben.
Anweisungen
1 Kopieren Sie den folgenden Code:
Option Explicit
Funktion FileOrDirExists (Pfadname As String) As Boolean
'Macro Purpose: Function returns TRUE if the specified file
' or folder exists, false if not.
'PathName : Supports Windows mapped drives or UNC
' : Supports Macintosh paths
'File usage : Provide full file path and extension
'Folder usage : Provide full folder path
' Accepts with/without trailing "\" (Windows)
' Accepts with/without trailing ":" (Macintosh)
Dim iTemp As Integer
'Ignore errors to allow for error evaluation
On Error Resume Next
iTemp = GetAttr(PathName)
'Check if error exists and set response appropriately
Select Case Err.Number
Case Is = 0
FileOrDirExists = True
Case Else
FileOrDirExists = False
End Select
'Resume error checking
On Error Goto 0
EndFunction
Sub TestItWithWindows()
'Macro Purpose: To test the FileOrDirExists function with Windows
'Only included to demonstrate the function. NOT required for normal use!
Dim sPath As String
'Change your directory here
sPath = "C:\Test.xls"
'Test if directory or file exists
If FileOrDirExists(sPath) Then
MsgBox sPath & " exists!"
Else
MsgBox sPath & " does not exist."
End If
EndSub
Sub TestItWithMacintosh()
'Macro Purpose: To test the FileOrDirExists function with a Macintosh
'Only included to demonstrate the function. NOT required for normal use!
Dim sPath As String
'Change your directory here
sPath = "HardDriveName:Documents:Test.doc"
'Test if directory or file exists
If FileOrDirExists(sPath) Then
MsgBox sPath & " exists!"
Else
MsgBox sPath & " does not exist."
End If
EndSub
2 Öffnen Sie Excel, und drücken Sie "Alt-F11" Visual Basic-Editor eingeben.
3 Klicken Sie auf "Einfügen" und klicken Sie auf "Module".
4 Füge den Code in dem rechten Fensterbereich durch Drücken von "Strg-" V."
5 Ändern Sie "text.xls" in den Dateinamen, den, dem Sie suchen.
6 Mit "F5" um die Prozedur auszuführen. Das Verfahren liefert ein Popupfenster, sagen Sie, ob die Datei vorhanden ist.