qcw911 发表于 2016-9-20 09:38:58

使用API方法 实现CommonDialog的方法

本人 win7 64位 CAD2011
怎么才能实现 对话框选取文件呢?
用VBA来实现

找了好久没找到合适的方法

vbcad 发表于 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






qcw911 发表于 2016-9-22 09:55:03

&H80000 Or &H200   多选时候的参数

zzyong00 发表于 2016-10-9 22:46:55

64位,不是这么定义的:Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) 、

qcw911 发表于 2016-10-11 11:43:59

zzyong00 发表于 2016-10-9 22:46
64位,不是这么定义的:Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFile ...

什么意思,这个函数现在可以用,没问题的
页: [1]
查看完整版本: 使用API方法 实现CommonDialog的方法