6个简单而有用的VBA自定义函数
(2018-05-24 16:41:00)
标签:
excelvba代码 |
分类: VBA专区 |
VBA内部有许多有用的内建函数,但对于好些常规任务(或常见的问题)仍然需要编写自定义函数,这些问题是比较通用的。如检查一个文件是否存在等。
这里包括了6个非常有用自定义VBA函数,你可以简单的复制这些代码到你的模块中,以备方便调用。
这些函数包括:
FileExists:检查一个文件是否存在
– Returns TRUE if a particular file exists.
FileNameOnly:从路径中提取文件名
– Extracts the filename part of a path/filename string.
PathExists:检查路径是否存在
– Returns TRUE if a particular path exists.
RangeNameExists:区域名称是否已存在
– Returns TRUE if a particular range name exists.
SheetExists:检查工作表是否存在
– Returns TRUE if a particular sheet exists.
WorkBookIsOpen:检查工作簿是否打开
– Returns TRUE if a particular workbook is open.
具体代码如下:
The FileExists Function
1.Private
Function FileExists(fname)
As Boolean2.'
Returns TRUE if the file exists 3. Dim
x As
String4. x
= Dir(fname)5. If
x <> "" Then
FileExists = True
_6. Else
FileExists = False7.End
FunctionThe FileNameOnly Function
01.Private
Function FileNameOnly(pname)
As String02.'
Returns the filename from a path/filename
string 03. Dim
i As Integer,
length As Integer,
temp As String04. length
= Len(pname)05. temp
= ""06. For
i = length To 1
Step -107. If
Mid(pname, i, 1) = Application.PathSeparator
Then08. FileNameOnly
= temp09. Exit
Function10. End
If11. temp
= Mid(pname, i, 1) & temp12. Next
i13. FileNameOnly
= pname14.End
FunctionThe PathExists Function
1.Private
Function PathExists(pname)
As Boolean2.'
Returns TRUE if the path exists 3. Dim
x As
String4. On
Error Resume
Next5. x
= GetAttr(pname) And
06. If
Err = 0 Then PathExists =
True _7. Else
PathExists = False8.End
FunctionThe RangeNameExists Function
01.Private
Function RangeNameExists(nname)
As Boolean02.'
Returns TRUE if the range name exists 03. Dim
n As
Name04. RangeNameExists
= False05. For
Each n In
ActiveWorkbook.Names06. If
UCase(n.Name) = UCase(nname)
Then07. RangeNameExists
= True08. Exit
Function09. End
If10. Next
n11.End
FunctionThe SheetExists Function
1.Private
Function SheetExists(sname)
As Boolean2.'
Returns TRUE if sheet exists in the active
workbook 3. Dim
x As
Object4. On
Error Resume
Next5. Set
x = ActiveWorkbook.Sheets(sname)6. If
Err = 0 Then SheetExists =
True _7. Else
SheetExists = False8.End
FunctionThe WorkbookIsOpen Function
1.Private
Function WorkbookIsOpen(wbname)
As Boolean2.'
Returns TRUE if the workbook is open 3. Dim
x As
Workbook4. On
Error Resume
Next5. Set
x = Workbooks(wbname)6. If
Err = 0 Then WorkbookIsOpen
= True _7. Else
WorkbookIsOpen =
False8.End
Function
加载中…