' Begin ----------------------------------------------------------------

Sub ReadTableInFile(TableName, FileName)

  'Reset the session
  session.findById("wnd[0]/tbar[0]/okcd").text = "/n"
  session.findById("wnd[0]/tbar[0]/btn[0]").press

  'Open TAC SE16
  session.findById("wnd[0]/tbar[0]/okcd").text = "/nSE16"
  session.findById("wnd[0]/tbar[0]/btn[0]").press

  'View table
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").text = _
    TableName
  session.findById("wnd[0]/tbar[1]/btn[7]").press
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Set display to ALV Grid view

  ' Open user specific parameters dialog
  ' Attention: Here is a language specific code
  Set Menu = session.findById("wnd[0]/mbar")
  Set Einstellungen = Menu.FindByName("Einstellungen", "GuiMenu")
  Set BenutzerPar = Einstellungen.FindByName("Benutzerparameter...", _
    "GuiMenu")
  BenutzerPar.Select()

  'Set the display
  Set ALVGridView = session.findById("wnd[1]/usr/tabsG_TABSTRIP/" & _
    "tabp0400/ssubTOOLAREA:SAPLWB_CUSTOMIZING:0400/" & _
    "radRSEUMOD-TBALV_GRID")
  If ALVGridView.Selected = vbFalse Then
    ALVGridView.select()
  End If
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  Set BenutzerPar = Nothing
  Set Einstellungen = Nothing
  Set Menu = Nothing

  'Get rows and columns
  Set table = session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell")
  Rows = table.RowCount() - 1
  Cols = table.ColumnCount() - 1

  'Write the table to a CSV file
  Set oFile = CreateObject("Scripting.FileSystemObject")
  If IsObject(oFile) Then
    Set CSVFile = oFile.CreateTextFile(FileName, True)
    If IsObject(CSVFile) Then

      'Get the title of all columns in the first line
      Set Columns = table.ColumnOrder()
      For j = 0 To Cols
        If j = Cols Then
          CSVFile.Write(CStr(Columns(j)))
        Else
          CSVFile.Write(CStr(Columns(j)) & ";")
        End If
      Next
      CSVFile.WriteLine("")

      For i = 0 To Rows
        For j = 0 To Cols
          If j = Cols Then
            CSVFile.Write(table.GetCellValue(i, CStr(Columns(j))))
          Else
            CSVFile.Write(table.GetCellValue(i, CStr(Columns(j))) & ";")
          End If
        Next

        'Each 32 lines actualize the grid
        If i Mod 32 = 0 Then
          table.SetCurrentCell i, CStr(Columns(0))
        End If

        'Carriage and return after a line
        If i <> Rows Then
          CSVFile.WriteLine("")
        End If

      Next

      CSVFile.Close
    End If
  End If

  Set ALVGridView = Nothing
  Set Columns = Nothing
  Set table = Nothing

End Sub

'Main
Set SapGuiAuto = GetObject("SAPGUI")
Set application = SapGuiAuto.GetScriptingEngine
Set connection = application.Children(0)
Set session = connection.Children(0)

'Read the table SFLIGHT in a file
ReadTableInFile "SFLIGHT", "C:\\Dummy\\SFlight.csv"

' End ------------------------------------------------------------------