Search code examples
excelvbaautocad

AutoCAD & Excel Connection


I have spent more than 3 hours searching for a way to connect Excel & AutoCAD Using VBA.

I have found some Sample Codes but it cant Detect the running excel File instead it creates new excel session.

Sub excel_con()

Dim excelApp As Object
Dim wbkObj As Object
Dim shtObj As Object

 'make sure Excel reference is set!!
 Set excelApp = GetObject(, "Excel.Application")
 If Err <> 0 Then
 Err.Clear
 Set excelApp = CreateObject("Excel.Application")
 If Err <> 0 Then
 MsgBox "Could not start Excel", vbExclamation
 End
 End If
 End If
 excelApp.Visible = True
 Set wbkObj = excelApp.Workbooks.Add
 Set shtObj = excelApp.Worksheets(1)
End Sub

This Excel is already running when I run the code enter image description here

New Excel Session is opened Book6 refers to how many times i ran the code 6 times enter image description here


Solution

    1. You are allways creating a new workbok

    Set wbkObj = excelApp.Workbooks.Add

    1. Every new workbok is created in a new Excel instace.
    2. It is not possible, with the code you have, to know if an existent or a new excel instance is being used, unless you debug it step by step.

    Try this code below, to see what you get and to move on from there.

    Sub get_excel()
    
    Dim excelApp As Object
    'make sure Excel reference is set!!
    Set excelApp = GetObject(, "Excel.Application")
    If Err <> 0 Then
        MsgBox "Could not get any valid Excel objet", vbExclamation
    else
        excelApp.Visible = True
    End If
    End Sub