VBA|文件处理01:查看文件信息-sub文件

VBA|文件处理01:查看文件信息-sub文件

要查看文件信息,可以使用传统VBA语句和FSO对象模型两种方式。

1 使用传统VBA语句查看文件信息

Sub 查看文件属性()

Dim sFileName As String, sType As String

Dim i As Integer, iType As Integer

sFileName = Application.GetOpenFilename(, , "选择文件")

If sFileName = "False" Then Exit Sub '用户选择“取消”则退出程序

With Worksheets("文件属性")

.Cells.Clear '清除工作表内容

.Cells(1, 1) = "文件名:"

.Cells(1, 2) = Mid(sFileName, InStrRev(sFileName, "\") + 1) '取文件名

.Cells(2, 1) = "文件大小:"

.Cells(2, 2) = FileLen(sFileName) & "Byte"

.Cells(3, 1) = "文件类型:"

iType = GetAttr(sFileName)

If iType And vbNormal = 0 Then

sType = "常规文件"

ElseIf iType And vbReadOnly Then

sType = "只读文件"

ElseIf iType And vbHidden Then

sType = "隐藏文件"

ElseIf iType And vbSystem Then

sType = "系统文件"

ElseIf iType And vbArchive Then

sType = "备份文件"

ElseIf iType And vbDirectory Then

sType = "文件夹"

End If

.Cells(3, 2) = sType

.Cells(4, 1) = "最后修改时间:"

.Cells(4, 2) = FileDateTime(sFileName)

.Columns("A:B").AutoFit

End With

End Sub

执行上面的代码,在打开的对话框中选择一个文件后,即可显示如下的一些信息:

文件名:获取文件信息.xls
文件大小:48640Byte
文件类型:常规文件
最后修改时间:2017/11/10 10:08

2 使用FSO对象模型查看文件信息

Sub 用FSO显示文件属性()

Dim fso As New FileSystemObject, oFile As File

Dim sType As String, str1 As String, sFileName As String

sFileName = Application.GetOpenFilename(, , "选择文件")

If sFileName = "False" Then Exit Sub '用户选择“取消”则退出程序

Set oFile = fso.GetFile(sFileName)

With oFile

If (.Attributes And Normal) = Normal Then sType = sType & "普通"

If (.Attributes And ReadOnly) = ReadOnly Then sType = sType & "只读"

If (.Attributes And Hidden) = Hidden Then sType = sType & "隐藏"

If (.Attributes And System) = System Then sType = sType & "系统"

If (.Attributes And Directory) = Directory Then sType = sType & "文件夹"

If (.Attributes And Archive) = Archive Then sType = sType & "存档"

End With

With Worksheets("文件属性")

.Range("A1:B8").ClearContents

.Cells(1, 1) = "文件名称:"

.Cells(1, 2) = oFile.Name

.Cells(2, 1) = "短文件名:"

.Cells(2, 2) = oFile.ShortName

.Cells(3, 1) = "文件路径:"

.Cells(3, 2) = oFile.Path

.Cells(4, 1) = "文件类型:"

.Cells(4, 2) = sType

.Cells(5, 1) = "文件大小:"

.Cells(5, 2) = Round(oFile.Size / 1024, 2) & "KB"

.Cells(6, 1) = "所在驱动器:"

.Cells(6, 2) = oFile.Drive

.Cells(7, 1) = "所在文件夹:"

.Cells(7, 2) = oFile.ParentFolder

.Cells(8, 1) = "创建时间:"

.Cells(8, 2) = oFile.DateCreated

.Columns("A:B").AutoFit

End With

Set oFile = Nothing

Set fso = Nothing

End Sub

执行上面的代码,在打开的对话框中选择一个文件后,即可显示如下的一些信息:

文件名:获取文件信息.xls
文件大小:48640Byte
文件类型:常规文件
最后修改时间:2017/11/10 10:08

-End-

推荐阅读