Search code examples
vbasap-gui

SAP Column IDs to an Array


I am trying to get the column IDs of an SAP Grid. I can get the Name of a column from a selected cell with.

    session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").CurrentCellColumn

This returns "AUFNR" which is the Id I am looking for for the selected column. How do I cycle through the rest of the columns and put the Ids into an array to use for data extraction

Full code for the above.

Sub Get_Column_ID()
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPapp = SapGuiAuto.GetScriptingEngine
Set SAPCon = SAPapp.Children(0)
Set session = SAPCon.Children(0)
MyGrid = "wnd[0]/usr/cntlGRID1/shellcont/shell"

Range("A1").Value = session.findByID(MyGrid).CurrentCellColumn



End Sub

Solution

  • You could try the following :

    Sub Get_Column_ID() 
     Set SapGuiAuto = GetObject("SAPGUI")
     Set SAPapp = SapGuiAuto.GetScriptingEngine
     Set SAPCon = SAPapp.Children(0)
     Set session = SAPCon.Children(0)
     set myGrid = session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell")
    
     allRows = myGrid.RowCount - 1
     allCols = myGrid.ColumnCount - 1
    
     Dim columns As Object
     Set columns = myGrid.ColumnOrder
    
     For i = 0 To allCols
      myGrid.setCurrentCell 0, columns(i)
      ActiveSheet.Cells(1, i + 1).Value = myGrid.CurrentCellColumn
     Next
    
     For j = 0 To allRows
      For i = 0 To allCols
       ActiveSheet.Cells(j + 2, i + 1).Value = myGrid.GetCellValue(j, columns(i))
      Next
     Next
    
    End Sub
    

    Regards, ScriptMan