Thanks for looking into it. I took your improved code and put it into the model.
Here is the interesting part. It gave the same HRESULT error the second time I ran it.
Some interesting things to note are:
- once excel is open then the rule executes fine, I have only got errors on the excel creation.
- If I have the rule open, and use the save & run command I dont get any problems
I ran this rule on a colleagues computer, and I got different errors, "Could not get the active X component" (or something like that), It also failed on the save & run command from inside the rule, and I got my error handling message for losing the shared variable.
I am a bit mystified as to what the source of the errors is, because it doesnt always behave the same on different computers and seems to error out on different sections of code.
Code below, it is barely changed from what you had, I tried adding in some try catch code to pinpoint where it was going wrong.
Sub Main()
Dim strDoc As Inventor.PartDocument = ThisApplication.ActiveDocument
Dim propSet As PropertySet = strDoc.PropertySets("Inventor User Defined Properties")
Dim i As Integer = 0
Dim j As Integer = 0
Dim Counter_Start As Integer = 1
Dim ExcelRunning As Boolean = False
'See if Excel is already running
For Each p In Process.GetProcesses
If p.ProcessName = "EXCEL" Then
ExcelRunning = True
End If
Next
Dim excelApp As Object
Dim excelWorkbook As Object
If ExcelRunning = False Then
excelApp = CreateObject("Excel.Application")
excelApp.Visible = True
excelApp.DisplayAlerts = False
excelWorkbook = excelApp.Workbooks.Add
ElseIf ExcelRunning = True Then
If SharedVariable.Exists("Counter_End") Then
Counter_Start = SharedVariable("Counter_End")
Else
MessageBox.Show("iLogic has lost the shared variable", "Error Handling")
Return
End If
excelApp = GetObject(, "Excel.Application")
excelApp.Visible = True
excelApp.DisplayAlerts = False
excelWorkbook = excelApp.ActiveWorkBook
End If
For Each prop In propSet
strPropName = prop.Name
If strPropName.Contains("Qty")
i = i + 1
End If
Next
With excelApp
.Range("C" & Counter_Start).Select
.ActiveCell.FormulaR1C1 = iProperties.Value("Project", "Stock Number")
.Range("A" & (Counter_Start+1)).Select
.ActiveCell.FormulaR1C1 = "Qty"
.Range("B" & (Counter_Start+1)).Select
.ActiveCell.FormulaR1C1 = "Code"
.Range("C" & (Counter_Start+1)).Select
.ActiveCell.FormulaR1C1 = "Description"
End With
For j = 1 To i
ItemCode = "Item" & j & "_Code"
ItemQty = "Item" & j & "_Qty"
ItemDescription = "Item" & j & "_Description"
With excelApp
.Range("A" & (j+Counter_Start+1)).Select
.ActiveCell.FormulaR1C1 = iProperties.Value("Custom", ItemQty)
.Range("B" & (j+Counter_Start+1)).Select
.ActiveCell.FormulaR1C1 = iProperties.Value("Custom", ItemCode)
.Range("C" & (j+Counter_Start+1)).Select
.ActiveCell.FormulaR1C1 = iProperties.Value("Custom", ItemDescription)
End With
Next
excelApp.Columns.AutoFit
SharedVariable("Counter_End") = (j + Counter_Start + 1)
excelApp = Nothing
End Sub