Search code examples
exceltcltdom

Setting cell value using TCOM/TCL with function call


I'm trying to assign the cell values in TCOM using function call. But i See the exact function name getting printed.

set application [::tcom::ref createobject "Excel.Application"]
set workbooks [$application Workbooks]
$application DisplayAlerts False
set workbook [$workbooks Open "\\$filename.csv"]
set worksheets [$workbook Worksheets]
set worksheet [$worksheets Item [expr 1]]
set cells_worksheet1 [$worksheet Cells] 

$cells_worksheet1 Item 27 B $Attribute

I want to replace $cells_worksheet1 Item 27 B $Attribute to $cells_worksheet1 Item 27 B {[getAttribute]} where getAttribute function returns $attribute. Any idea how to do this?


Solution

  • As far as I can see from the Excel API, you get a Range back from the Cells property, and a further Range back from its Item member. You can then access the properties of that individual item using the property accessors.

    # Assuming your largely-perfect code from your question...
    
    set cell [$cells_worksheet1 Item 27 B]
    set orientation [$cell Orientation]    ;# Arbitrary example of getting a property
    $cell Orientation 42                   ;# Setting the property
    

    You can get the name of the property to manipulate from sources other than literals:

    proc getAttribute {} {
        return "Orientation"
    }
    puts "orientation is [$cell [getAttribute]]" ;# Note, *no* {braces} involved!
    

    That won't necessarily work well for all properties though; the problem isn't that you can't ask for them, but rather some want additional information passing in when you fetch them and others take extra work to extract once fetched as they are compound objects themselves. It's hard to give better advice without knowing exactly what you're planning to do with it.


    The issue with the braces was that Tcl treats them as being exact substitution-free literals. That's great when you're declaring a procedure, but not so useful when you want to call that procedure and use the results.