如何用vba判断excel的文件格式?

excel 2003使用的是复合文档文件格式。

excel 2007(含)开始微软引进了Open XML 文档格式,实际上是ZIP文件格式。

这两种文件格式都在文件头有特征的标识符。

比如复合文档文件格式的文件头部的开始有8个字节的特征标识符:0xD0CF11E0A1B11AE1。

ZIP文件格式的文件头部的开始有4个字节的特征标识符:0x504B0304。

根据以上的知识,可以使用如下的代码判断excel文件的文件格式:

Declare Function GetOpenFileName Lib "comdlg32.dll" Alias _
     "GetOpenFileNameA" (lpofn As OPENFILENAME) As Long
 Type OPENFILENAME
     lStructSize As Long
     hwndOwner As Long
     hInstance As Long
     lpstrFilter As String
     lpstrCustomFilter As String
     nMaxCustFilter As Long
     nFilterIndex As Long
     lpstrFile As String
     nMaxFile As Long
     lpstrFileTitle As String
     nMaxFileTitle As Long
     lpstrInitialDir As String
     lpstrTitle As String
     flags As Long
     nFileOffset As Integer
     nFileExtension As Integer
     lpstrDefExt As String
     lCustData As Long
     lpfnHook As Long
     lpTemplateName As String
End Type
Function GOFN() As String
    Dim sOFN As OPENFILENAME
    With sOFN
        .lStructSize = Len(sOFN)
        '设置打开文件对话框中的文件筛选字符串对
        .lpstrFilter = "Excel文件(*.xl*)" & Chr(0) & "*.xl*" & Chr(0) & "Word文件(*.do*)" _
        & Chr(0) & "*.do*" & Chr(0) & "PPT文件(*.pp*)" & Chr(0) & "*.pp*" & Chr(0) & "所有文件(*.*)" & Chr(0) & "*.*" _
        & Chr(0) & Chr(0)
        '设置文件完整路径和文件名的缓冲区
        .lpstrFile = Space(1024)
        '设置文件完整路径和文件名的最大字符数,一定要比lpstrFile参数指定的字符数多1,用于存储结尾Null字符。
        .nMaxFile = 1025
    End With
    i = GetOpenFileName(sOFN)
    If i <> 0 Then
        With sOFN
            sFileName = Trim(.lpstrFile)
            GOFN = Left(sFileName, Len(sFileName) - 1)
        End With
    Else
        GOFN = ""
    End If
    Debug.Print GOFN, Len(GOFN)
End Function
Sub OpenFile()
    sFilePath = GOFN
    If Len(sFilePath) = 0 Then
        End
    Else
        i = VBA.FreeFile
        Open sFilePath For Binary Access Read As i
        Dim arr(1 To 8) As Byte
        Get i, 1, arr
        Dim arrCDF(1 To 8) As Byte
        arrCDF(1) = &HD0
        arrCDF(2) = &HCF
        arrCDF(3) = &H11
        arrCDF(4) = &HE0
        arrCDF(5) = &HA1
        arrCDF(6) = &HB1
        arrCDF(7) = &H1A
        arrCDF(8) = &HE1
        Dim arrZIP(1 To 4) As Byte
        arrZIP(1) = &H50
        arrZIP(2) = &H4B
        arrZIP(3) = &H3
        arrZIP(4) = &H4
        j = VBA.InStrB(1, arr, arrCDF, vbBinaryCompare)
        n = VBA.InStrB(1, arr, arrZIP, vbBinaryCompare)
        If j > 0 Then
        Debug.Print "选择的文件为复合文档格式"
        End If
        If n > 0 Then
        Debug.Print "选择的文件为ZIP文档格式"
        End If
        Debug.Print j, n
    End If
End Sub
       

发表评论