作者:绿色风
分类:
时间:2022-08-17
浏览:158
楼主 amulee |
Q:如何使用API函数FindFirstFile查找文件? A:利用API函数FindFirstFile、FindNextFile可以实现文件的查找。其用法和VBA中的Dir函数有些类似。请参考以下代码:
- 'API声明
- Public Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
- Public Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
- Public Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
- '最大路径长度和文件属性常量的定义
- Public Const MAX_PATH = 260
- '这里有文件属性,包括文件夹、隐藏等。对应dwFileAttributes
- Public Const FILE_ATTRIBUTE_ARCHIVE = &H20
- Public Const FILE_ATTRIBUTE_COMPRESSED = &H800
- Public Const FILE_ATTRIBUTE_DIRECTORY = &H10
- Public Const FILE_ATTRIBUTE_HIDDEN = &H2
- Public Const FILE_ATTRIBUTE_NORMAL = &H80
- Public Const FILE_ATTRIBUTE_READONLY = &H1
- Public Const FILE_ATTRIBUTE_SYSTEM = &H4
- Public Const FILE_ATTRIBUTE_TEMPORARY = &H100
- '文件结构
- Type FILETIME
- dwLowDateTime As Long
- dwHighDateTime As Long
- End Type
- Type WIN32_FIND_DATA
- dwFileAttributes As Long
- ftCreationTime As FILETIME
- ftLastAccessTime As FILETIME
- ftLastWriteTime As FILETIME
- nFileSizeHigh As Long
- nFileSizeLow As Long
- dwReserved0 As Long
- dwReserved1 As Long
- cFileName As String * MAX_PATH
- cAlternate As String * 14
- End Type
- Sub Main()
- Dim FindData As WIN32_FIND_DATA
- Dim FindHandle As Long
- Dim FindNextHandle As Long
- Dim FPath As String
- Dim FName As String
- FPath = "D:\"
- FName = "*.txt"
- '开始API查找,找到的文件属性在FindData里
- FindHandle = FindFirstFile(FPath & FName, FindData)
- '如果找到,则返回不为0。发生错误返回-1
- If FindHandle <> 0 And FindHandle <> -1 Then
- Debug.Print fDelInvaildChr(FindData.cFileName)
- '查找下一个,用法差不多
- Do
- FindNextHandle = FindNextFile(FindHandle, FindData)
- If FindNextHandle <> 0 And FindNextHandle <> -1 Then
- Debug.Print fDelInvaildChr(FindData.cFileName)
- Else
- Exit Do
- End If
- Loop
- End If
- '关闭文件搜索
- FindClose FindHandle
- End Sub
- '去除非法字符
- Public Function fDelInvaildChr(str As String) As String
- On Error Resume Next
- Dim i As Long
- For i = Len(str) To 1 Step -1
- If Asc(Mid(str, i, 1)) <> 0 And Asc(Mid(str, i, 1)) <> 32 Then
- fDelInvaildChr = Left(str, i)
- Exit For
- End If
- Next
- End Function
API搜索.rar |
2楼 wbzxz |
amulee老师,您的附件上传错啦,嘿嘿。 |
免责声明
有感于原ExcelTip.Net留存知识的价值及部分知识具有的时间限定性因素,
经与ExcelTip.Net站长Apolloh商议并征得其同意,
现将原属ExcelTip.Net的知识帖采集资料于本站点进行展示,
供有需要的人士查询使用,也慰缅曾经的论坛时代。
所示各个帖子的原作者如对版权有异议,
可与本人沟通提出,或于本站点留言,我们会尽快处理。
在此,感谢ExcelTip.Net站长Apolloh的支持,感谢本站点所有人**绿色风(QQ:79664738)**的支持与奉献,特此鸣谢!
------本人网名**KevinChengCW(QQ:1210618015)**原ExcelTip.Net总版主之一