如何在vba中使用api函数GetOpenFileName选择打开文件?

api函数GetOpenFileName可以弹出一个打开对话框,通过打开对话框可以选择一个或者多个文件打开。

但是实际上并未真正打开文件,而是获取要打开文件的完整路径、文件名等信息。

它的C++语法如下:

BOOL WINAPI GetOpenFileName(
  _Inout_ LPOPENFILENAME lpofn
);

VB语法如下:

Declare Function GetOpenFileName Lib "comdlg32.dll" Alias _
     "GetOpenFileNameA" (lpofn As OPENFILENAME) As Long

其中lpofn参数是一个OPENFILENAME结构,这个结构包含了选择文件后的各种信息。

它的成员如下:

typedef struct tagOFN {
  DWORD         lStructSize;
  HWND          hwndOwner;
  HINSTANCE     hInstance;
  LPCTSTR       lpstrFilter;
  LPTSTR        lpstrCustomFilter;
  DWORD         nMaxCustFilter;
  DWORD         nFilterIndex;
  LPTSTR        lpstrFile;
  DWORD         nMaxFile;
  LPTSTR        lpstrFileTitle;
  DWORD         nMaxFileTitle;
  LPCTSTR       lpstrInitialDir;
  LPCTSTR       lpstrTitle;
  DWORD         Flags;
  WORD          nFileOffset;
  WORD          nFileExtension;
  LPCTSTR       lpstrDefExt;
  LPARAM        lCustData;
  LPOFNHOOKPROC lpfnHook;
  LPCTSTR       lpTemplateName;
#if (_WIN32_WINNT >= 0x0500)
  void          *pvReserved;
  DWORD         dwReserved;
  DWORD         FlagsEx;
#endif 
} OPENFILENAME, *LPOPENFILENAME;

如果在弹出的对话框中选择了文件,并且单击了确定按钮,则GetOpenFileName函数返回非0,其中OPENFILENAME结构的lpstrFile元素将存储选择文件的完整路径和文件名。

如果用户没有选择文件或者取消或者关闭了对话框,则GetOpenFileName函数返回0。

以下是一个通用的返回选择文件完整路径和文件名的函数:

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

 

       

发表评论