Some Useful VBA FunctionsVBA has many useful built-in functions, but it lacks the ability to perform many common tasks. For example, if your application needs to determine if a particular file exists, you need to write your own code to make that determination. This tip contains VBA code for six simple, but very useful functions. You can simply copy the code and paste it to your module.
The FileExists FunctionPrivate Function FileExists(fname) As Boolean
' Returns TRUE if the file exists
Dim x As String
x = Dir(fname)
If x <> "" Then FileExists = True _
Else FileExists = False
End Function
The FileNameOnly FunctionPrivate Function FileNameOnly(pname) As String
' Returns the filename from a path/filename string
Dim i As Integer, length As Integer, temp As String
length = Len(pname)
temp = ""
For i = length To 1 Step -1
If Mid(pname, i, 1) = Application.PathSeparator Then
FileNameOnly = temp
Exit Function
End If
temp = Mid(pname, i, 1) & temp
Next i
FileNameOnly = pname
End Function
The PathExists FunctionPrivate Function PathExists(pname) As Boolean
' Returns TRUE if the path exists
Dim x As String
On Error Resume Next
x = GetAttr(pname) And 0
If Err = 0 Then PathExists = True _
Else PathExists = False
End Function
The RangeNameExists Function
|