VBA代碼調用瀏覽檔案夾對話方塊的幾種方法

來源:互聯網
上載者:User

 

1、使用API方法

'【型別宣告】
Private Type BROWSEINFO
    hWndOwner      As Long
    pIDLRoot       As Long
    pszDisplayName As Long
    lpszTitle      As Long
    ulFlags        As Long
    lpfnCallback   As Long
    lParam         As Long
    iImage         As Long
End Type
'【API聲明】
Private Declare Function SHGetPathFromIDList Lib "shell32.dll" _
    Alias "SHGetPathFromIDListA" (ByVal pidl As Long, _
    ByVal pszPath As String) As Long
Private Declare Function SHBrowseForFolder Lib "shell32.dll" _
    Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
Private Declare Function lstrcat Lib "kernel32" _
    Alias "lstrcatA" (ByVal lpString1 As String, _
    ByVal lpString2 As String) As Long
Private Declare Function OleInitialize Lib "ole32.dll" _
    (lp As Any) As Long
Private Declare Sub OleUninitialize Lib "ole32" ()
   
Private Const BIF_USENEWUI = &H40
Private Const MAX_PATH = 260
'【自訂函數】
Public Function GetFolder_API(sTitle As String, Optional vFlags As Variant) As String
  Dim lpIDList As Long
  Dim sBuffer As String
  Dim BInfo As BROWSEINFO
 
  If IsMissing(vFlags) Then vFlags = BIF_USENEWUI
 
  Call OleInitialize(ByVal 0&)
 
  With BInfo
    .lpszTitle = lstrcat(sTitle, "")
    .ulFlags = vFlags
  End With
 
  lpIDList = SHBrowseForFolder(BInfo)
 
  If (lpIDList) Then
    sBuffer = Space(MAX_PATH)
    SHGetPathFromIDList lpIDList, sBuffer
    sBuffer = Left(sBuffer, InStr(sBuffer, vbNullChar) - 1)
   
    If sBuffer <> "" Then GetFolder_API = sBuffer
  End If
 
  Call OleUninitialize
End Function
'【使用方法】
Sub Test()
MsgBox GetFolder_API("選擇檔案夾")
End Sub

2、使用Shell.Application方法

Sub GetFloder_Shell()

    Set objShell = CreateObject("Shell.Application")
        Set objFolder = objShell.BrowseForFolder(0, "選擇檔案夾", 0, 0)
            If Not objFolder Is Nothing Then
                MsgBox objFolder.self.path
            End If
        Set objFolder = Nothing
    Set objShell = Nothing

End Sub

3、使用FileDialog方法

Sub GetFloder_FileDialog()
    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    If fd.Show = -1 Then MsgBox fd.SelectedItems(1)
    Set fd = Nothing
End Sub

以上方法在WINXP+OFFICE2003中測試通過

 

----------------------------------------------------------------------------------------------------------

URL:http://www.officexy.com/Articles/office/VBABasic/20061026103436069.htm

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.