vba 浏览文件夹对话框调用的几种方法
2016-06-29来源:

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中测试通过

推荐信息
Baidu
map