cad vba 打开excel并弹窗打开指定文件、通过fso弹窗打开dwg

news/2024/7/21 6:37:00 标签: excel, CAD vba

 CAD vba 代码实现打开excel,并通过对话框选择xls文件,并打开此文件进行下一步操作。代码如下:

excel.activeworkbook.sheets(1) ''

excel对象下activeworkbook,再往下是sheets对象,(1)为第一个表,

thisworkbook是vba代码所在的工作簿。


Option Explicit
#If VBA7 Then
Private Declare PtrSafe Function ts_apiGetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (tsFN As tsFileName) As Boolean
Private Declare PtrSafe Function ts_apiGetSaveFileName Lib "comdlg32.dll" Alias "GetSaveFileNameA" (tsFN As tsFileName) As Boolean
Private Declare PtrSafe Function CommDlgExtendedError Lib "comdlg32.dll" () As Long
Private Declare PtrSafe Function SHGetPathFromIDList Lib "shell32.dll" Alias _
"SHGetPathFromIDListA" (ByVal pidl As LongPtr, ByVal pszPath As String) As LongPtr
Private Declare PtrSafe Function SHBrowseForFolder Lib "shell32.dll" Alias _
"SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As LongPtr
Private Const BIF_RETURNONLYFSDIRS = &H1
Private Type BROWSEINFO
            hOwner As LongPtr
            pidlRoot As LongPtr
            pszDisplayName As String
            lpszTitle As String
            ulFlags As LongPtr
            lpfn As LongPtr
            lParam As LongPtr
            iImage As LongPtr
End Type
Private Type tsFileName
   lStructSize As Long
   hwndOwner As LongPtr
   hInstance As LongPtr
   strFilter As String
   strCustomFilter As String
   nMaxCustFilter As Long
   nFilterIndex As Long
   strFile As String
   nMaxFile As Long
   strFileTitle As String
   nMaxFileTitle As Long
   strInitialDir As String
   strTitle As String
   flags As Long
   nFileOffset As Integer
   nFileExtension As Integer
   strDefExt As String
   lCustData As Long
   lpfnHook As LongPtr
   lpTemplateName As String
End Type
 
' Flag Constants
Private Const tscFNAllowMultiSelect = &H200
Private Const tscFNCreatePrompt = &H2000
Private Const tscFNExplorer = &H80000
Private Const tscFNExtensionDifferent = &H400
Private Const tscFNFileMustExist = &H1000
Private Const tscFNPathMustExist = &H800
Private Const tscFNNoValidate = &H100
Private Const tscFNHelpButton = &H10
Private Const tscFNHideReadOnly = &H4
Private Const tscFNLongNames = &H200000
Private Const tscFNNoLongNames = &H40000
Private Const tscFNNoChangeDir = &H8
Private Const tscFNReadOnly = &H1
Private Const tscFNOverwritePrompt = &H2
Private Const tscFNShareAware = &H4000
Private Const tscFNNoReadOnlyReturn = &H8000
Private Const tscFNNoDereferenceLinks = &H100000
 
Public Function GOFN( _
    Optional ByRef rlngflags As Long = 0&, _
    Optional ByVal strInitialDir As String = "", _
    Optional ByVal strFilter As String = "dwg文件 (*.dwg)" & vbNullChar & "*.dwg" _
    & vbNullChar & "All Files (*.*)" & vbNullChar & "*.*", _
    Optional ByVal lngFilterIndex As Long = 1, _
    Optional ByVal strDefaultExt As String = "", _
    Optional ByVal strFileName As String = "", _
    Optional ByVal strDialogTitle As String = "", _
    Optional ByVal fOpenFile As Boolean = True) As Variant
'On Error GoTo GOFN_Err
    
    Dim tsFN As tsFileName
    Dim strFileTitle As String
    Dim fResult As Boolean
 
    ' Allocate string space for the returned strings.
    strFileName = Left(strFileName & String(256, 0), 256)
    strFileTitle = String(256, 0)
 
    ' Set up the data structure before you call the function
    With tsFN
        .lStructSize = LenB(tsFN)
        '.hwndOwner = Application.hWndAccessApp
        .strFilter = strFilter
        .nFilterIndex = lngFilterIndex
        .strFile = strFileName
        .nMaxFile = Len(strFileName)
        .strFileTitle = strFileTitle
        .nMaxFileTitle = Len(strFileTitle)
        .strTitle = strDialogTitle
        .flags = rlngflags
        .strDefExt = strDefaultExt
        .strInitialDir = strInitialDir
        .hInstance = 0
        .strCustomFilter = String(255, 0)
        .nMaxCustFilter = 255
        .lpfnHook = 0
    End With
   
    ' Call the function in the windows API
   
        fResult = ts_apiGetOpenFileName(tsFN)
    If fResult Then
        rlngflags = tsFN.flags
        GOFN = tsTrimNull(tsFN.strFile)
    Else
        GOFN = Null
        MsgBox "您未选择"
        End
    End If
 
End Function
Public Function GSFN( _
    Optional ByRef rlngflags As Long = 0&, _
    Optional ByVal strInitialDir As String = "", _
    Optional ByVal strFilter As String = "dwg文件 (*.dwg)" & vbNullChar & "*.dwg" _
    & vbNullChar & "All Files (*.*)" & vbNullChar & "*.*", _
    Optional ByVal lngFilterIndex As Long = 1, _
    Optional ByVal strDefaultExt As String = "", _
    Optional ByVal strFileName As String = "", _
    Optional ByVal strDialogTitle As String = "", _
    Optional ByVal fOpenFile As Boolean = False) As Variant
'On Error GoTo tsGetFileFromUser_Err
    
    Dim tsFN As tsFileName
    Dim strFileTitle As String
    Dim fResult As Boolean
 
    ' Allocate string space for the returned strings.
    strFileName = Left(strFileName & String(256, 0), 256)
    strFileTitle = String(256, 0)
 
    ' Set up the data structure before you call the function
    With tsFN
        .lStructSize = LenB(tsFN)
        '.hwndOwner = Application.hWndAccessApp
        .strFilter = strFilter
        .nFilterIndex = lngFilterIndex
        .strFile = strFileName
        .nMaxFile = Len(strFileName)
        .strFileTitle = strFileTitle
        .nMaxFileTitle = Len(strFileTitle)
        .strTitle = strDialogTitle
        .flags = rlngflags
        .strDefExt = strDefaultExt
        .strInitialDir = strInitialDir
        .hInstance = 0
        .strCustomFilter = String(255, 0)
        .nMaxCustFilter = 255
        .lpfnHook = 0
    End With
   
        fResult = ts_apiGetSaveFileName(tsFN)
    If fResult Then
        rlngflags = tsFN.flags
        GSFN = tsTrimNull(tsFN.strFile)
    Else
        GSFN = Null
        MsgBox "您未保存"
        End
    End If
 
End Function
 
' Trim Nulls from a string returned by an API call.
Private Function tsTrimNull(ByVal strItem As String) As String
On Error GoTo tsTrimNull_Err
    Dim I As Integer
   
    I = InStr(strItem, vbNullChar)
    If I > 0 Then
        tsTrimNull = Left(strItem, I - 1)
    Else
        tsTrimNull = strItem
    End If
    
tsTrimNull_End:
    On Error GoTo 0
    Exit Function
 
 
tsTrimNull_Err:
    Beep
    MsgBox Err.Description, , "Error: " & Err.Number _
    & " in function basBrowseFiles.tsTrimNull"
    Resume tsTrimNull_End
 
End Function

Public Function GOFOLDER() As String
On Error GoTo Err_GOFOLDER
    Dim x As LongPtr, bi As BROWSEINFO, dwIList As LongPtr
    Dim szPath As String, wPos As Integer
   
    With bi
        '.hOwner = hWndAccessApp
        .lpszTitle = "请选择文件夹"
        .ulFlags = BIF_RETURNONLYFSDIRS
    End With
   
    dwIList = SHBrowseForFolder(bi)
    szPath = Space$(512)
    x = SHGetPathFromIDList(ByVal dwIList, ByVal szPath)
   
    If x Then
        wPos = InStr(szPath, Chr(0))
        GOFOLDER = Left$(szPath, wPos - 1)
    Else
        GOFOLDER = ""
        MsgBox "您未选择"
        End
    End If
Exit_GOFOLDER:
    Exit Function
Err_GOFOLDER:
    MsgBox Err.Number & " - " & Err.Description
    Resume Exit_GOFOLDER
End Function
#Else
Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (lpofn As OPENFILENAME) As Long
Declare Function GetSaveFileName Lib "comdlg32.dll" Alias "GetSaveFileNameA" (lpofn As OPENFILENAME) As Long
Declare Function SHBrowseForFolder Lib "SHELL32.DLL" (lpBrowseInfo As BROWSEINFO) As Long
Declare Function SHGetPathFromIDList Lib "SHELL32.DLL" (ByVal pidl As Long, ByVal pszPath As String) As Long
Public choice As String
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
Public Type BROWSEINFO
    hOwner As Long
    pidlRoot As Long
    pszDisplayName As String
    lpszTitle As String
    ulFlags As Long
    lpfn As Long
    lParam As Long
    iImage As Long
End Type

Function GOFOLDER(Optional message) As String
Dim bInfo As BROWSEINFO
Dim path As String
Dim r As Long, x As Long, pos As Integer
bInfo.pidlRoot = 0
bInfo.lpszTitle = ""
bInfo.ulFlags = &H1
x = SHBrowseForFolder(bInfo)
path = Space$(256)
r = SHGetPathFromIDList(ByVal x, ByVal path)
If r Then
    pos = InStr(path, Chr(0))
    GOFOLDER = Left(path, pos - 1)
Else
    GOFOLDER = ""
    MsgBox "您未选择"
    End
End If
End Function
Function GOFN() As String
    Dim sOFN As OPENFILENAME
    With sOFN
        .lStructSize = Len(sOFN)
        
       .lpstrFilter = "dwg文件(*.dwg)" & Chr(0) & "*.dwg" & Chr(0) & "dxf文件(*.dxf)" & Chr(0) & "*.dxf" & Chr(0) & "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)
        .nMaxFile = 1025
    End With
    Dim sFileName As String

    If GetOpenFileName(sOFN) <> 0 Then
        With sOFN
            sFileName = Trim(.lpstrFile)
            GOFN = Left(sFileName, Len(sFileName) - 1)
        End With
    Else
        GOFN = ""
          MsgBox "您已取消,请重新选择"
        End
    End If
End Function
Function GSFN() As String
    Dim sSFN As OPENFILENAME
    With sSFN
        .lStructSize = Len(sSFN)
        '设置保存文件对话框中的文件筛选字符串对
       .lpstrFilter = "dwg文件(*.dwg)" & Chr(0) & "*.dwg" & Chr(0) & "dxf文件(*.dxf)" & Chr(0) & "*.dxf" & Chr(0) & "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
     
    Dim sFileName As String
    If GetSaveFileName(sSFN) <> 0 Then
        With sSFN
            sFileName = Trim(.lpstrFile)
            GSFN = Left(sFileName, Len(sFileName) - 1)
        End With
    Else
        GSFN = ""
        MsgBox "您已取消,请重新选择"
        End
       
    End If
'    Debug.Print GSFN, Len(GSFN)

End Function
#End If



Sub CAD打开excel_cadvba实现()
Dim excel As Object
Dim excelSheet As Object
    ' Start Excel
    On Error Resume Next
    
    Set excel = GetObject(, "Excel.Application")
    
    If Err <> 0 Then
        Err.Clear
        Set excel = CreateObject("Excel.Application")
            
        If Err <> 0 Then
            MsgBox "Could not load Excel.", vbExclamation
            End
        End If
    End If
    excel.Visible = True
'    MsgBox GOFN
    excel.Workbooks.Open FileName:=GOFN
'    On Error GoTo errorcontrol
'errorcontrol: MsgBox Err.Number & " - " & Err.Description
'End

End Sub

若不想通过windows api方法 (代码太长),可通过引用office库,调用excel的fso函数弹窗返回路径名,然后可通过documents.open打开dwg文件。

Function cad引用打开dwg()
'前提是:工具——引用——打开Microsoft office库
'On Error Resume Next
Dim excel As Object
'Set scripting.filesystemobject = GetObject(, "scripting.filesystemobject.Application")

Set excel = CreateObject("excel.Application")
'excel.Visible = True
excel.workbooks.Add
With excel.FileDialog(msoFileDialogOpen)
    .Title = "请选择你要的文件"
    .AllowMultiSelect = True
    .InitialFileName = "C:\Users\Administrator\Desktop\"
    .Filters.Clear
    .Filters.Add "excel files", "*.xls,*.xlsx,*.dwg"
    If .show = True Then
    Set gof = .SelectedItems
'    .Execute '打开excel时启用
    Dim sname As String
    sname = gof.Item(1)
    Documents.Open sname
    excel.Quit '退出excel
    Else: Exit Function
    End If
End With
End Function

Sub a()
Call cad引用打开dwg
ZoomExtents
ThisDrawing.Regen acActiveViewport
End Sub

cad引用打开excel方法:

Function cad引用打开excel()
'前提是:工具——引用——打开Microsoft office库
'On Error Resume Next
Dim excel As Object
'Set scripting.filesystemobject = GetObject(, "scripting.filesystemobject.Application")

Set excel = CreateObject("excel.Application")
excel.Visible = True
excel.workbooks.Add
With excel.FileDialog(msoFileDialogOpen)
    .Title = "请选择你要的文件"
    .AllowMultiSelect = True
    .InitialFileName = "C:\Users\Administrator\Desktop\"
    .Filters.Clear
    .Filters.Add "excel files", "*.xls,*.xlsx,*.dwg"
    If .show = True Then
    Set gof = .SelectedItems
    .Execute '打开excel时启用
'    Dim sname As String
'    sname = gof.Item(1)
'    Documents.Open sname
'    excel.Quit '退出excel
    Else: Exit Function
    End If
End With
End Function

Sub a()
Call cad引用打开excel
End Sub


http://www.niftyadmin.cn/n/5449413.html

相关文章

[AIGC] Redis基础命令集详细介绍

Redis是一个强大的开源的键-值存储系统&#xff0c;被广泛应用于各种应用程序中。在使用Redis时&#xff0c;我们需要掌握一些基本的Redis命令来操作存储在其上的数据。这篇文章将向你介绍一些基本的Redis命令&#xff0c;让你能够更好地使用和理解Redis。 文章目录 启动Redis…

【Android】【Bluetooth Stack】Android Bluetooth架构分析(超详细)

1. 精讲蓝牙协议栈&#xff08;Bluetooth Stack&#xff09;&#xff1a;SPP/A2DP/AVRCP/HFP/PBAP/IAP2/HID/MAP/OPP/PAN/GATTC/GATTS/HOGP等协议理论 2. 欢迎大家关注和订阅&#xff0c;【蓝牙协议栈】和【Android Bluetooth Stack】专栏会持续更新中.....敬请期待&#xff01…

【centos8 离线安装tar】centos8.0 离线安装tar包

系统tar 命令无法使用&#xff0c;在没有外网的情况下应该如何&#xff1f; 打开清华镜像源 https://mirrors.tuna.tsinghua.edu.cn/centos-vault/7.8.2003/os/x86_64/Packages/ 下载tar 包 安装命令 rpm -Uvh tar-1.26-35.el7.x86_64.rpm --nodeps --force

ClickHouse--11--物化视图

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 1.物化视图什么是物化视图? 1.1 普通视图1.2 物化视图1.3 优缺点1.4 基本语法1.5 在生产环境中创建物化视图1.6 AggregatingMergeTree 表引擎3.1 概念3.2 Aggregat…

不可或缺的工作学习助手,早用早享受

好东西&#xff0c;自然要分享出来大家一起使用。本次推荐阿里系通义系列之一的“通义听悟”&#xff0c;看名字就可以猜个大概&#xff0c;与声音有关。 没错&#xff0c;就是用AI快速帮你处理音频的&#xff0c;至于哪些音频&#xff0c;看你的使用场景。 会议日程太多&#…

【Redis】优惠券秒杀

全局唯一ID 全局唯一ID生成策略&#xff1a; UUIDRedis自增snowflake算法数据库自增 Redis自增ID策略&#xff1a;每天一个key&#xff0c;方便统计订单量ID构造是 时间戳 计数器 Component public class RedisIdWorker {// 2024的第一时刻private static final long BEGIN…

FastAPI+React全栈开发02 什么是FARM技术栈

Chapter01 Web Development and the FARM Stack 02 What is the FARM stack and how does it fit together? FastAPIReact全栈开发02 什么是FARM技术栈 It is important to understand that stacks aren’t really special, they are just sets of technologies that cover…

阿里云倚天云服务器怎么样?如何收费?

阿里云倚天云服务器CPU采用倚天710处理器&#xff0c;租用倚天服务器c8y、g8y和r8y可以享受优惠价格&#xff0c;阿里云服务器网aliyunfuwuqi.com整理倚天云服务器详细介绍、倚天710处理器性能测评、CIPU架构优势、倚天服务器使用场景及生态支持&#xff1a; 阿里云倚天云服务…