- 积分
- 2399
- 明经币
- 个
- 注册时间
- 2014-1-22
- 在线时间
- 小时
- 威望
-
- 金钱
- 个
- 贡献
-
- 激情
-
|
发表于 2016-9-20 09:38:59
|
显示全部楼层
本帖最后由 vbcad 于 2016-9-21 19:40 编辑
在网上找的代码,经过验证,完全可用!
调用方法
filepath=OpenFile(0)
或者
debug.print OpenFile(0)
Private 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
Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
'文件打开对话框
'函数:OpenFile
'参数:WinHwnd 调用此函数的HWND
' BoxLabel 设置对话框的标签.
' StartPath 设置初始化路径.
' FilterStr 文件过滤.
' Flag 标志.(参考MSDN)
'返回值:String 文件名.
'例子:
Public Function OpenFile(WinHwnd As Long, _
Optional BoxLabel As String = "", _
Optional StartPath As String = "", _
Optional FilterStr = "*.*|*.*", _
Optional Flag As Variant = &H8 Or &H200000) As String
Dim Rc As Long
Dim pOpenfilename As OPENFILENAME
Dim Fstr1() As String
Dim Fstr As String
Dim i As Long
Const MAX_Buffer_LENGTH = 256
On Error Resume Next
If Len(Trim$(StartPath)) > 0 Then
If Right$(StartPath, 1) <> "\" Then StartPath = StartPath & "\"
If Dir$(StartPath, vbDirectory + vbHidden) = "" Then
StartPath = App.Path
End If
Else
StartPath = App.Path
End If
If Len(Trim$(FilterStr)) = 0 Then
Fstr = "*.*|*.*"
End If
Fstr = ""
Fstr1 = Split(FilterStr, "|")
For i = 0 To UBound(Fstr1)
Fstr = Fstr & Fstr1(i) & vbNullChar
Next
With pOpenfilename
.hwndOwner = WinHwnd
.hInstance = App.hInstance
.lpstrTitle = BoxLabel
.lpstrInitialDir = StartPath
.lpstrFilter = Fstr
.nFilterIndex = 1
.lpstrDefExt = vbNullChar & vbNullChar
.lpstrFile = String(MAX_Buffer_LENGTH, 0)
.nMaxFile = MAX_Buffer_LENGTH - 1
.lpstrFileTitle = .lpstrFile
.nMaxFileTitle = MAX_Buffer_LENGTH
.lStructSize = Len(pOpenfilename)
.flags = Flag
End With
Rc = GetOpenFileName(pOpenfilename)
If Rc Then
OpenFile = Left$(pOpenfilename.lpstrFile, pOpenfilename.nMaxFile)
Else
OpenFile = ""
End If
End Function
|
|