Nwlapcug.com


Come determinare se esiste un File in Excel VBA



Visual Basic for Applications (VBA) è un sottoinsieme di Visual Basic che viene utilizzato per adattare i programmi di Microsoft Office in base alle esigenze. Quando si scrive in un file in VBA, è buona norma assicurarsi che quel particolare file esista prima di tentare di scrivere in esso. Se si desidera trovare se esiste un file in Excel, è necessario compilare un modulo VBA che fa il trucco. Per poter utilizzare questa funzione, si dovrebbe avere qualche precedente esperienza con la programmazione di VB.

Istruzioni

1

Copiare il codice riportato di seguito:

Option Explicit

Funzione FileOrDirExists (PathName 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

End Function

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

End Sub

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

End Sub

2

Aprire Excel e premere "Alt-F11" per inserire l'Editor di Visual Basic.

3

Fare clic su "Inserisci" e quindi fare clic su "Modulo".

4

Incollare il codice nel riquadro a destra premendo "Ctrl-" V."

5

Modificare "text. xls" al nome del file che stai cercando.

6

Premere "F5" per eseguire la procedura. La procedura restituirà una finestra popup che ti dice se il file esiste.