'Adobe InDesign script to affect only selected Table/Text Frame

I am new to scripting and copied this one below and it works great but not all tables are the same in the document and I just want to affect the selected tables/text frames.

Is there an easy way to make this code work the way I am looking to do.

var myDoc = app.activeDocument;
var myWidths = [.5,.35,.44,.44];
for(var T=0; T < myDoc.textFrames.length; T++){
  for(var i=0; i < myDoc.textFrames[T].tables.length; i++){
    for(var j=0; j < myWidths.length; j++){
      myDoc.textFrames[T].tables[i].columns[j].width = myWidths[j];
    }
  }
}

Thanks for any help, just starting to dive into InDesign Scripting and understand it.



Solution 1:[1]

Yes, it can be done quite easy:

var myWidths = [.5,.35,.44,.44];

var sel = app.selection;
if (sel.length != 1) exit();
var frame = sel[0];
if (frame.constructor.name != 'TextFrame') exit();

for (var i = 0; i < frame.tables.length; i++) {
    for (var j = 0; j < myWidths.length; j++) {
        frame.tables[i].columns[j].width = myWidths[j];
    }
}

It will work for one selected text frame.

If you need to process several selected frames here is another variant of the code:

var myWidths = [.5,.35,.44,.44];
var frames = app.selection
var f = frames.length

while(f--) {
    if (frames[f].constructor.name != 'TextFrame') continue; 
    var tables = frames[f].tables;
    var t = tables.length;
    while(t--) {
        var table = tables[t];
        var c = table.columns.length;
        while(c--) {
            table.columns[c].width = myWidths[c];
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RobC