Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations cowski on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

SolidWorks macro with Excel

Status
Not open for further replies.

mihalj

Mechanical
Apr 15, 2009
40
Hi,
I am creating macro where I first open excel file, then I am supposed by VBA from SW macro access already opened excel file. Just to mention, below code works, however vba opens about 10 copies of same excel file while it is working and I think the reason for it is For loop in the beginning. Is there any other way for me to directly access already opened excel file. Each excel file would have different name, therefore vba should first find a name of the excel file directly if possible (without for loop), then call the excel file, pull data from it,then close excel file and all its copies if made.
Here is the code:

Sub main()

Set objExcel = GetObject(, "Excel.Application")
For Each wbExcel In objExcel.Workbooks
excelFullName = wbExcel.FullName
Next

Set wbExcel = Workbooks.Open(excelFullName)
Set wsExcel = wbExcel.Sheets("Sheet1")

strP7 = wsExcel.Cells(7, 15) ' takes value from cell
strP8 = wsExcel.Cells(8, 15) ' takes value from cell

dblP7 = CDbl(strP7)
dblP8 = CDbl(strP8)

wbExcel.Close SaveChanges:=False


Set xlApp = Nothing
Set objExcel = Nothing
Set wbExcel = Nothing
Set wsExcel = Nothing
----------macro continues with SW data and double values taken from excel-------------
 
Replies continue below

Recommended for you

I do not think the for loop at the beginning is opening the files. If you only have a single Excel file open in a single instance of Excel, it should only loop once. Below are two modifications that might work.

Eric

Code:
Sub main()

Set objExcel = GetObject(, "Excel.Application")
Set wbExcel = objExcel.Workbooks(1)
Set wsExcel = wbExcel.Sheets("Sheet1")

strP7 = wsExcel.Cells(7, 15) ' takes value from cell
...
Or
Code:
Sub main()

Set objExcel = GetObject(, "Excel.Application")
For Each wbExcel In objExcel.Workbooks
  Set wsExcel = wbExcel.Sheets("Sheet1")
Next

strP7 = wsExcel.Cells(7, 15) ' takes value from cell
...
 
Sorry, I did not reply earlier as I completely forgot I did post question on a forum. In short, I did resolve the issue same day using "Kill Taskbar" command to close any excel activity after passing all data from excel to variables inside the macro before reshuffling everything and assigning values to SolidWorks variables. Thanks for help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor