Search notes:

Excel Object Model

Some fundamental Excel objects include:
Other interesting Excel COM automatization objects, imho, are:
Application
AutoFilter An AutoFilter object allows to hide or show rows based on criterias put on the values in the cells of these rows.
AutoRecover Control automatic recovery features for a workbook
Axes A chart's axes object contains all axis objects that belong to that chart.
Axis
Border A border object represents one of the four edges of a Range.
Button A button allows a user to execute a macro
Chart
Charts
ChartArea
ChartFormat
ChartGroup
ChartObject A chartObject is a container for a chart object.
ChartTitle
Comment
Connections A collection of WorkbookConnection
DisplayFormat represents display settings for the corresponding range.
DropDown
ErrorBars An errorBar is an element in charts, especially for bar/column and scatter charts.
Errors
Filter «condition» of a column in a range with an autoFilter.
Font Specifies the attributes of a text's font.
FormatCondition
Global A «hidden» object that allows to access objects without prefixing them with application in VBA code (for example cells.… instead of application.cells.…).
Hyperlink
Interior
LegendEntry
LegendKey A legend key links a legend entry with its associated series or trendline.
ListColumn
ListObject
ListRow
Model PowerPivot Model
Name A name object refers to named range.
Names
OLEObject
OLEObjects
OLEDBConnection
Pane A «pane» of a Window.
Pages
PageSetup Page size, margins, orientation etc.
PivotCache A pivot cache provides the data for a PivotTable report.
PivotField
PivotTable A PivotTable object represents a PivotTable report.
PivotLayout This object seems to connect a chart with the pivotTable that it gets the data from.
PlotArea
ProtectedViewWindow A protected view window displays a workbook from a potentially unsafe locations.
Point
QueryTable
Range A range is a set of one or more cells.
Series
SeriesCollection
Shape
Shapes
Sheets The collection of all sheets (not only worksheets).
SheetViews Allows to access the available WorksheetView objects of a Window.
Style Describes a «style» which can be applied to ranges.
Sort
SortField Stores attributes which influences the behavior of worksheet, listObject and autoFilter objects.
TextFrame2 The same(?) as the Office object TextRange2.
Validation Allows to limit the possible values that can be entered in a range (so called data validation)
Window
Workbook A Workbook object is the object that corresponds to an Excel file (*.xlsm, *.xlsx, etc.). The currently active workbook is obtained with application.activeWorkbook.
Workbooks Is the collection of all currently open workbooks.
WorkbookConnection A WorkbookConnection objects stores the information that is required to obtain data from an external data source (that is not located in the Workbook itself.)
WorkbookQuery represents a query that was created by Power Query.
Worksheet Each worksheet object represents the individual worksheets in a workbook.
Worksheets
WorksheetFunction
WorksheetView «Look and Feel» settings like DisplayFormulas, DisplayGridlines or DisplayHeadings.
Catching events
Here's a template that hopefully demonstrates how an Excel workbook can be created from scratch in VBA.

misc - Formulas - rand

'
'   ..\..\runVBAFilesInOffice.vbs -excel rand -c Go
'
'   Compare with -> randbetween()

sub Go()

  range("a1").formula = "=rand()"

end sub

Github repository about-MS-Office-object-model, path: /Excel/misc/Formulas/rand.bas

misc - Formulas - randBetween

'
'   ..\..\runVBAFilesInOffice.vbs -excel randBetween -c Go
'
'   Note, the function returns an integer.
'
'   Compare with -> rand()

sub Go()

  range("a1").formula = "=randBetween(100, 110)"
  range("a2").formula = "=randBetween(100, 110)"
  range("a3").formula = "=randBetween(100, 110)"

end sub

Github repository about-MS-Office-object-model, path: /Excel/misc/Formulas/randBetween.bas

misc - Formulas - if

'
'   ..\..\runVBAFilesInOffice.vbs -excel if -c Go
'
sub Go()

    range("a1:b10").formula = "=rand()"

  ' Note:  «a1<b1» dynamically changes with the rows in which
  '        they appear.
    range("c1:c10").formula = "=if( a1<b1 , ""less"" , ""greater or equal"")"

end sub
Github repository about-MS-Office-object-model, path: /Excel/misc/Formulas/if.bas

misc - Formulas - sumif

'
'   ..\..\runVBAFilesInOffice.vbs -excel sumif -c main
'
sub main()

    cells(1,1) = 13: cells(1,2) = 1
    cells(2,1) = 21: cells(2,2) = 0
    cells(3,1) = 34: cells(3,2) = 0
    cells(4,1) = 47: cells(4,2) = 1
    cells(5,1) = 56: cells(5,2) = 0

  ' Calculate the sum of numbers found in a1:a5 whose corresponding
  ' value in b1:b5 equals 1.
  '
  ' The sum will be 60 = 13 + 47
    cells(7,1).formula = "=sumif(b1:b5, 1, a1:a5)"

    activeWorkbook.saved = true

end sub
Github repository about-MS-Office-object-model, path: /Excel/misc/Formulas/sumif.bas

misc - Formulas - formulaR1C1

'
'   ..\..\runVBAFilesInOffice.vbs -excel formulaR1C1 -c Go
'
sub Go()

    range("b2").formula = "=rand()"
    range("c2").formula = "=rand()"

  ' Note, the formula turns into
  '    «  =IF( B2 < C2; "less"; "greater or equal" )  »
  ' in the produced formula
    range("d2").formulaR1C1 = "=if( rc[-2] < rc[-1] , ""less"" , ""greater or equal"" )"

end sub
Github repository about-MS-Office-object-model, path: /Excel/misc/Formulas/formulaR1C1.bas

PivotTable - example 1

'
'   ..\..\..\runVBAFilesInOffice.vbs -excel example_01 -c Go %CD%
'

Sub Go(cur_working_dir as string)

    dim pivot_sheet            as workSheet
    dim pivot_cache            as pivotCache
    dim pivot_table            as pivotTable
    
    dim pivot_table_upper_left as range
    dim pf_col_1               as pivotField
    dim pf_col_2               as pivotField
'

    call importCSV(cur_working_dir & "\pivot.csv", activeSheet, range("$a$1"), "csv_data")
'
    set pivot_sheet = sheets.add

    set pivot_cache = activeWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= "csv_data", Version:=xlPivotTableVersion14)

    set pivot_table_upper_left = pivot_sheet.range("C3")
        
    set pivot_table = pivot_cache.CreatePivotTable ( TableDestination:= pivot_table_upper_left )


    set pf_col_1 = pivot_table.pivotFields("col_1")
    set pf_col_2 = pivot_table.pivotFields("col_2")

    pf_col_1.orientation = xlRowField
    pf_col_2.orientation = xlColumnField

    call pivot_table.addDataField (pf_col_2, "Count of col_2", xlCount)

    activeWorkbook.saved = true

End Sub

private sub importCSV(csv_file_name as string, sheet_ as workSheet, range_ as range, name_ as string) ' { 
  '
  ' -> https://github.com/ReneNyffenegger/runVBAFilesInOffice/blob/master/Excel/ObjectModel/QueryTable/load_CSV.bas
  '
  

    With ActiveSheet.QueryTables.Add(                 _ 
               Connection:= "TEXT;" & csv_file_name , _
               Destination:=range_)

        .name                 = name_
        .fieldNames = True
        .rowNumbers = False
        .preserveFormatting = True
        .textFilePlatform = 437
        .textFileStartRow = 1
        .textFileParseType = xlDelimited
        .textFileTextQualifier = xlTextQualifierDoubleQuote
        .textFileConsecutiveDelimiter = False
        .textFileCommaDelimiter = True
        .textFileTrailingMinusNumbers = True
        .refresh BackgroundQuery:=False

    end with


end sub

Github repository about-MS-Office-object-model, path: /Excel/PivotTable/example_01.bas

PivotTable - example 2

'
'   ..\..\..\runVBAFilesInOffice.vbs -excel example_02 -c Go %CD%
'

Sub Go(cur_working_dir as string)

    dim pivot_sheet            as workSheet
    dim pivot_cache            as pivotCache
    dim pivot_table            as pivotTable
    
    dim pivot_table_upper_left as range
    dim pf_col_1               as pivotField
    dim pf_col_2               as pivotField

    call importCSV(cur_working_dir & "\pivot.csv", activeSheet, range("$a$1"), "csv_data")
'
    set pivot_sheet = sheets.add

    set pivot_cache = activeWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= "csv_data", Version:=xlPivotTableVersion14)

    set pivot_table_upper_left = pivot_sheet.range("C3")
        
    set pivot_table = pivot_cache.CreatePivotTable ( TableDestination:= pivot_table_upper_left )

    set pf_col_1 = pivot_table.pivotFields("col_1")
    set pf_col_2 = pivot_table.pivotFields("col_2")

    call pivot_table.addDataField(pf_col_2, "Count of col_2", xlCount)

    pf_col_1.orientation = xlRowField
    pf_col_1.position    = 1

    pf_col_2.orientation = xlColumnField
    pf_col_2.position    = 1

    activeWorkbook.saved = true

End Sub

private sub importCSV(csv_file_name as string, sheet_ as workSheet, range_ as range, name_ as string) ' { 
  '
  ' -> https://github.com/ReneNyffenegger/runVBAFilesInOffice/blob/master/Excel/ObjectModel/QueryTable/load_CSV.bas
  '
  

    With ActiveSheet.QueryTables.Add(                 _ 
               Connection:= "TEXT;" & csv_file_name , _
               Destination:=range_)

        .name                 = name_
        .fieldNames = True
        .rowNumbers = False
        .preserveFormatting = True
        .textFilePlatform = 437
        .textFileStartRow = 1
        .textFileParseType = xlDelimited
        .textFileTextQualifier = xlTextQualifierDoubleQuote
        .textFileConsecutiveDelimiter = False
        .textFileCommaDelimiter = True
        .textFileTrailingMinusNumbers = True
        .refresh BackgroundQuery:=False

    end with


end sub

Github repository about-MS-Office-object-model, path: /Excel/PivotTable/example_02.bas

Shapes - addLine

'
'   ..\..\..\runVBAFilesInOffice.vbs -excel addLine -c Go
'

public sub Go()

  dim line as shape

  set line = create_line("b2", "e2")

  set line = create_line("c3", "f9")



  activeWorkbook.saved = true

end sub

private function create_line(fromCell as string, toCell as string) as shape

  set line = activeSheet.shapes.addline(  _
                beginX :=  range(fromCell).left + range(fromCell).width   / 2, _
                beginY :=  range(fromCell).top  + range(fromCell).height  / 2, _
                endX   :=  range(toCell  ).left + range(toCell  ).width   / 2, _
                endY   :=  range(toCell  ).top  + range(toCell  ).height  / 2  )

end function
Github repository about-MS-Office-object-model, path: /Excel/Shapes/addLine.bas

PageSetup - page

'
'  ..\..\..\runVBAFilesInOffice.vbs -excel page -c main
'

public sub main()

    dim ps as pageSetup

    set ps = activeSheet.pageSetup

    ps.paperSize   = xlPaperA4
    ps.orientation = xlLandscape

    activeWorkbook.saved = true

end sub
Github repository about-MS-Office-object-model, path: /Excel/PageSetup/page.bas

PageSetup - margins

'
'  ..\..\..\runVBAFilesInOffice.vbs -excel margins -c main
'

public sub main()

    dim ps as pageSetup

    set ps = activeSheet.pageSetup

    ps.leftMargin    = application.centimetersToPoints(0.5)
    ps.rightMargin   = application.centimetersToPoints(0.5)
    ps.topMargin     = application.centimetersToPoints(0.5)
    ps.bottomMargin  = application.centimetersToPoints(0.5)

    ps.footerMargin  = application.centimetersToPoints(0  )
    ps.headerMargin  = application.centimetersToPoints(0  )

    activeWorkbook.saved = true

end sub
Github repository about-MS-Office-object-model, path: /Excel/PageSetup/margins.bas

SetValueInRowAndColumn

'
' ..\runVBAFilesInOffice.vbs -excel SetValueInRowAndColumn -c Run
'
public sub Run() ' {

  dim row as long
  dim col as long

  for row = 1 to 10
  for col = 1 to row

      cells(row, col) = row * col

  next col
  next row

end sub ' }
Github repository about-MS-Office-object-model, path: /Excel/SetValueInRowAndColumn.bas

LineFormat - style (Also → Microsoft/Office/Excel/Object-Model/QueryTable/CSV[here])

'
'   ..\..\..\runVBAFilesInOffice.vbs -excel style -c Go
'

public sub Go()

  dim f as lineFormat

  call create_line("b2", "e2", msoLineSingle          )
  call create_line("b3", "e3", msoLineThickBetweenThin)
  call create_line("b4", "e4", msoLineThickThin       )
  call create_line("b5", "e5", msoLineThinThick       )
  call create_line("b6", "e6", msoLineThinThin        )

  activeWorkbook.saved = true

end sub

private sub create_line(fromCell as string, toCell as string, style_ as msoLineStyle) 

  dim line_   as shape
  dim format_ as lineFormat

  set line_ = activeSheet.shapes.addline(  _
                beginX :=  range(fromCell).left + range(fromCell).width   / 2, _
                beginY :=  range(fromCell).top  + range(fromCell).height  / 2, _
                endX   :=  range(toCell  ).left + range(toCell  ).width   / 2, _
                endY   :=  range(toCell  ).top  + range(toCell  ).height  / 2  )

  set format_ = line_.line

  format_.weight =     10
  format_.style  = style_

end sub
Github repository about-MS-Office-object-model, path: /Excel/LineFormat/style.bas

Misc

The Excel 15.0 (?) Object library seems to be identified by the GUID {00020813-0000-0000-C000-000000000046}.

See also

VBA Excel modules
Excel

Index