项目开发进行中,为了提高工作效率,减少错误率,不得不用到VBA去开发些使用的工具【应该感谢excel强大】
其中有一个很重要的应用就是读取某一目录中的文件
本文分享一个项目写的读取文件夹中文件的VBA方法
**************************************************************************
1,创建一个用于存放读出来文件信息的用户类型【应该是深受面向对象的影响吧】
Type serchFileInfor
fileCount As Integer
fileNames() As String
fileDirs() As String
fileFullNames() As String
End Type
2,编写取得文件信息的方法
sPath:要检索的文件路径
sFileSpec:检索规则,比如说【*.*】是指检索全部文件,【*.txt】是检索所谓扩展名是txt的文件
serchFileInfor:文件保存的地方,因为下面用到了递归,参数所以,这个东西就传来传去了。
Public Sub FileTreeSearch(ByVal sPath As String, ByVal sFileSpec As String, _
ByRef fileInfo As serchFileInfor)
Dim sDir As String
Dim sSubDirs() As String
Dim iIndex As Long
If Strings.Right(sPath, 1) <> "\" Then
sPath = sPath & "\"
End If
sDir = Dir(sPath & sFileSpec)
Do While Len(sDir)
fileInfo.fileCount = fileInfo.fileCount + 1
ReDim Preserve fileInfo.fileNames(1 To fileInfo.fileCount)
ReDim Preserve fileInfo.fileDirs(1 To fileInfo.fileCount)
ReDim Preserve fileInfo.fileFullNames(1 To fileInfo.fileCount)
fileInfo.fileNames(fileInfo.fileCount) = sDir
fileInfo.fileDirs(fileInfo.fileCount) = sPath
fileInfo.fileFullNames(fileInfo.fileCount) = sPath & sDir
sDir = Dir
Loop
iIndex = 0
sDir = Dir(sPath & "*.*", vbDirectory)
Do While Len(sDir)
If Strings.Left(sDir, 1) <> "." Then 'skip.and..
If GetAttr(sPath & sDir) And vbDirectory Then
iIndex = iIndex + 1
ReDim Preserve sSubDirs(1 To iIndex)
sSubDirs(iIndex) = sPath & sDir & "\"
End If
End If
sDir = Dir
Loop
For iIndex = 1 To iIndex
FileTreeSearch(sSubDirs(iIndex), sFileSpec, fileInfo)
Next iIndex
End Function
这样,要用到的信息都放到了【fileInfo】中了。
接下来要如何操作文件,都是接下来要做的事情了。