I'm trying to run a macro from Solidworks which involves opening a previously created excel sheet and running a few commands for formatting/organisation. I recorded the necessary macro and tried to past it into the VBA editor through Solidworks and I can't figure out how to get the code to run properly. When running the macro, Excel runs and opens the relevant sheet but none of the commands from Range("A1:C3"). Select
onwards works, it's just the unaltered data. Is there something I'm missing?
I'm choosing to run the command from SolidWorks for convenience/self-containment and it's much easier to import macros on different machines than excel. Thanks!
Sub RunExcelMacro()
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
Dim xlWB As Excel.Workbook
Set xlWB = xlApp.Workbooks.Open("F:\sheet.csv")
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Open "F:\sheet.csv"
On Error Resume Next
Excel.Application.Run "F:\sheet.csv"
Range("A1:C3").Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
etc...
End Sub
Your code is based in Excel as being the host application. Top level commands like Range
and Selection
run against the Application
object, which if you've copied this code to SolidWorks then the Application
object is no longer Excel
it's SolidWorks
.
You can use Excel application commands like this:
With objExcel
.Run "F:\sheet.csv"
.Range("A1:C3").Select
.Selection.Borders(xlDiagonalDown).LineStyle = xlNone
.Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With .Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
End With
etc...
Notice I've added leading dots to call those commands against the application in the with block.
2nd problem
You are trying to run a macro in a CSV
file. CSV files can't contain macros. You also didn't cite a macro name. If you want to run a macro in a foreign workbook you must first open a valid macro enabled workbook and then call the macro by name.
It would look like this:
objExcel.Run "F:\sheet.xlsm!MyMacroName"
So that .xlsm
file must exist and it must contain MyMacroName
for that to work.