Use Excel without goexcel

Use Excel without goexcel

SevInventor
Advocate Advocate
891 Views
8 Replies
Message 1 of 9

Use Excel without goexcel

SevInventor
Advocate
Advocate

Hello Experts,

I'm writing a rule to replace missing references and outdated old content center parts.

I have an excel file to get the path of the new valid contend center part filename with the connection to the old filename. They are on separate sheets of the excel file. The connection is the Material Number.

If found this code to use excel without the ilogic goexcel because on my computer (and others) there are always problems with the COM interface of excel.

 

https://forums.autodesk.com/t5/inventor-ilogic-and-vb-net-forum/problem-with-goexcel-findrow/m-p/700...

 

How can i search the old filename  and get the new filename on different sheets of the excel by using functions and subs see code below?

 
Sub Main()
Dim oExcelPath As String = "\\192.168.7.10\dessins$\Inventor\iLogic\Liste_materiau.xlsx"
If Not System.IO.File.Exists(oExcelPath) Then
	MessageBox.Show("Can't access the Excel file.", "Inaccessible file")
	Exit Sub
End If
Dim oExcelSheet As String = "Feuil1"
Dim oDoc As Document = ThisApplication.ActiveDocument
'Run juste si c'est un .ipt
If oDoc.DocumentType <> kPartDocumentObject Then Exit Sub
Dim propName As String = "Description_Materiau"
Dim propValue As String = "Description Materiau"
'Get a reference to the PropertySets
'We're really only using Design Tracking Properties in this case though
Dim oPropSet1 As PropertySet = oDoc.PropertySets.Item("Inventor User Defined Properties")
Dim oPropSet2 As PropertySet = oDoc.PropertySets.Item("Design Tracking Properties")
Dim oPropSet3 As PropertySet = oDoc.PropertySets.Item("Inventor Summary Information")
Dim oProp As Inventor.Property
Try
	oProp = oPropSet1(propName)
Catch
	oProp = oPropSet1.Add("", propName)
End Try
oProp.Value = propValue

Dim SN As String = oPropSet2.Item("Stock Number").Value
If SN = vbNullString Then
	MessageBox.Show("Le num�ro de mat�riel n'est pas entr�", "Stock Number non-entr�")
	Exit Sub
End If

'Start Excel
StartExcel(oExcelPath)
If oWS Is Nothing Then Exit Sub

'Get the column ID
Dim ColumnID As Integer = GetColumnID("Stock_Number")
If ColumnID = 0 Then
	MessageBox.Show("Column 'Stock_Number' was not found", "Wrong column name")
	StopExcel()
	Exit Sub
End If

'Get the Excel row
Dim RowID As Integer = GetRowID(ColumnID, SN)
ColumnID = GetColumnID(propName)
If RowID > 0 And ColumnID > 0 Then
	'Get value from the Excel cell
	oProp.Value = GetRowValue(ColumnID, RowID)
Else
	MessageBox.Show("Le num�ro de mat�riel n'existe pas dans la liste Excel. Ajouter le num�ro de mat�riel dans la liste ainsi que sa description et r�essayer.", "Description non-trouv�e")
End If

'Stop Excel
StopExcel()
End Sub

Private oExcel As Object = Nothing
Private oWB As Object = Nothing
Private oWS As Object = Nothing

Sub StartExcel(oExcelPath As String)
	Try
		oExcel = CreateObject("Excel.Application")
		oWB = oExcel.Workbooks.Open(oExcelPath)
		oWS = oWB.Sheets(1)
		oExcel.Visible = False
		oExcel.DisplayAlerts = False
		oWS.Activate
	Catch
		StopExcel()
	End Try
End Sub

Sub StopExcel()
	On Error Resume Next
	oWB.Close (True)
	oExcel.Quit()
End Sub

Function GetColumnID(oValue As String) As Integer
	If oWS Is Nothing Then Return 0
	Dim ID As Integer = 1
	Try
	While True
		Dim CV As String = oWS.Cells(1, ID).Value
		If CV = oValue Then Exit While
		If CV = vbNullString Then
			ID = 0
			Exit While
		End If
		ID = ID + 1
	End While
	Catch
	End Try
	Return ID
End Function

Function GetRowID(ColumnID As Integer, oValue As String) As Integer
	If oWS Is Nothing Then Return 0
	Dim ID As Integer = 1
	Try
	While True
		Dim CV As String = oWS.Cells(ID, ColumnID ).Value
		If CV = oValue Then Exit While
		If CV = vbNullString Then
			ID = 0
			Exit While
		End If
		ID = ID + 1
	End While
	Catch
	End Try
	Return ID
End Function

Function GetRowValue(ColumnID As Integer, RowID As String) As String
	If oWS Is Nothing Then Return vbNullString
	Dim ID As String = vbNullString
	Try
		ID = oWS.Cells(RowID, ColumnID ).Value
	Catch
	End Try
	Return ID
End Function
 
0 Likes
Accepted solutions (1)
892 Views
8 Replies
Replies (8)
Message 2 of 9

Michael.Navara
Advisor
Advisor

You have two possibilities.

  1. Create new sheet in excel where your relevant data is in one place. One line for one file. For this task you can use all excel functions
  2. Read your data from excel from multiple sheets. Now you get the first sheet in ExcelStart() method oWS = oWB.Sheets(1) but oWB.Sheets is a collection and you can iterate them using For Each loop for example. Than you can search in multiple sheets
0 Likes
Message 3 of 9

SevInventor
Advocate
Advocate

Hello Michael,

 

thanks a lot for the reply.

why not oWS = oWB.Sheets("sheetname") instead of oWS = oWB.Sheets(1). Because its a collection?

The excel file is alway the same and i dont have to writ there.

So i know the sheet number . Can it be accessed like oWS = oWB.Sheets(sheetnumber)?

 

thanks.

 

 

 

 

0 Likes
Message 4 of 9

Michael.Navara
Advisor
Advisor

In your code you use only the first sheet and you ask how to look in more sheets.

Can you share your excel workbook schema or sample? It is useful for better understanding. One or two lines per sheet is suitable.

0 Likes
Message 5 of 9

SevInventor
Advocate
Advocate

thanks again,

 

I want to search in the sheet "not valid" in Column Dateiname for a filename and get the Material Number from that row

search in the sheet valid for this Material Nummer

get the right row from column Materialnr. Take the value in column Dateiname for the replacement

 

 

0 Likes
Message 6 of 9

Michael.Navara
Advisor
Advisor

Are data in columns valid.Materialnr and notValid.Dateiname unique? In this case it is possible to use little different approach.

 

0 Likes
Message 7 of 9

SevInventor
Advocate
Advocate

Yes, they are unique

0 Likes
Message 8 of 9

Michael.Navara
Advisor
Advisor
Accepted solution

In this case (it is not true in sample sheet) you can use the following approach. In general it consists from few steps

  1. Start Excel and open workbook (line 18)
  2. Read data from excel to your collections. Dictionary(Of String, String) in my case (Line 62)
  3. Close Excel and workbook (Line 31)
  4. Use read data. (Line 48)
  5. Optionally you can store Dictionaries in SharedVariables and restore them later in the Inventor session. It saves time to open and read data from excel (Line 33)

My example omits any error handlings for clear and brevity.

If the values in columns are not unique, the ArgumentException (An element with the same key already exists in the Dictionary<TKey,TValue>) are thrown.

 

Very important lines:

23, 28 - You choose the key and value columns in the dictionaries. In valid and notValid has the reversed order. Also you can try to read this indices from first line of sheet as in your original sample

73 - Property Value2 returns cell values from sheet as two-dimensional array of objects. It is similar to excel sheet preview.

  

Sub Main()
MainInternal()
End Sub

Private oExcel As Object = Nothing
Private oWB As Object = Nothing
Private oWS As Object = Nothing

Private Sub MainInternal()

	Dim workbookFileName As String = "C:\Path\To\Worksheet\Kopie von Warengruppe 3100__9075 _ Ext. ipt_Kopie.xlsx"

	'Create collections for data from Excel
	Dim valid As Dictionary(Of String, String)
	Dim notValid As Dictionary(Of String, String)

	'Read data from excel to dictionaries
	StartExcel(workbookFileName)

	Dim notValidSheetName As String = "not valid"
	Dim notValidDateinameColumnIndex = 2
	Dim notValidMaterialNrColumnIndex = 3
	notValid = ReadSheatToDictionary(notValidSheetName, notValidDateinameColumnIndex, notValidMaterialNrColumnIndex)

	Dim validSheetName = "valid"
	Dim validDateinameColumnIndex = 2
	Dim validMaterialNrColumnIndex = 3
	valid = ReadSheatToDictionary(validSheetName, validMaterialNrColumnIndex, validDateinameColumnIndex)

	'Excel is no longer needed
	StopExcel()

	''Dictionaries can be stored in SharedVariables
	''for later use in Inventor session.
	''If ShaerdVariable not exists, is null or empty.
	''You can read them from excel as shown above

	''Store
	'SharedVariable("NotValidSheetData") = notValid
	'SharedVariable("ValidSheetData") = valid

	''Restore
	'notValid = SharedVariable("NotValidSheetData")
	'valid = SharedVariable("ValidSheetData")


	'-------------------------
	'Test it or use it

	Dim oldPart = "M12X1.5-40.IPT"
	Dim newPartExpected = "ISO 8676 - M12 X 1,5 X 40DIN EN_340076.IPT"

	Dim materialNr = notValid(oldPart)
	Dim newPart = valid(materialNr)

	Dim found = (newPart = newPartExpected)
	Logger.Debug(found)
	Logger.Debug(oldPart)
	Logger.Debug(newPart)
End Sub

Function ReadSheatToDictionary(sheetName As String, keyColumnIndex As Integer, valueColumnIndex As Integer) As Dictionary(Of String, String)

	'Read data from sheet to Dictionary(Of String, string)

	'Create new Dictionary collection
	Dim dictionary = New Dictionary(Of String, String)()

	'Get Excel.Worksheet named valid
	Dim workSheet = oWB.Sheets(sheetName)

	'Get all data from sheet as two dimensional array
	Dim workSheetData As Object(, ) = workSheet.UsedRange.Value2

	'Get rows count from data array
	Dim dataRowsCount = workSheetData.GetLength(0)

	'Convert two-dimensional array to dictionary collection
	For r = 1 To dataRowsCount
		Dim key As String = workSheetData(r, keyColumnIndex).ToString()
		Dim value As String = workSheetData(r, valueColumnIndex).ToString()

		'MaterialNr is set as key for search on 'valid' sheet data
		dictionary.Add(key, value)
	Next

	Return dictionary
End Function

Sub StartExcel(oExcelPath As String)
	Try
		oExcel = CreateObject("Excel.Application")
		oWB = oExcel.Workbooks.Open(oExcelPath)
		oWS = oWB.Sheets(1)
		oExcel.Visible = False
		oExcel.DisplayAlerts = False
		oWS.Activate
	Catch
		StopExcel()
	End Try
End Sub

Sub StopExcel()
	On Error Resume Next
	oWB.Close(True)
	oExcel.Quit()
End Sub

  

 

 

Message 9 of 9

SevInventor
Advocate
Advocate

looks great!

Thank you very much Michael!

 

The duplicates will be removed by the excel command remove duplicates.-->no problem

In the meantime i found out how to switch between the sheets by the sheetname.

I think your solution is much faster if there are many searches for filenames. 

👍

 

 

0 Likes