About the script: Here is a simple script that proportionately scales a table to fit the text column that contains it. This script works with the current table but can be easily expanded to work with all of the tables in a document or book.
Getting the data: Click your cursor in a table that needs to be scaled. You will need to collect some basic information in order to scale the table correctly. Here is commented code to set the needed data into variables.
// The selected table.
Set vTbl = SelectedTbl;
// The current width of the table.
Set vTblWidth = vTbl.TblWidth;
// The width of the column containing the table.
Set vColWidth = vTbl.TextLoc.Object.InTextObj.Width;
The vColWidth variable is the width of the column in a multi-column text frame. If the text frame only has one column, the column width is equal to the text frame width. If you have multiple columns, but want to scale the table to the width of the text frame, use the following lines in place of the last two lines above.
// The width of the text frame containing the table.
Set vColWidth = vTbl.TextLoc.Object.InTextFrame.Width;
Now, the script can do some math to figure out much to scale the table.
// Divide the column width by the table width.
Set vScaleFactor = vColWidth / vTblWidth;
How to scale the table?
The table's TblWidth property is read only, so you cannot use this to scale the table.
// This won't work.
Set vTbl.TblWidth = vTblWidth * vScaleFactor;
Instead, you have to change the width of each individual column of the table. These widths are stored in a MetricList called TblColWidths.
// Set a variable for the table column widths.
Set vWidths = vTbl.TblColWidths;
A metric list is a list of measurement values. In this case, there is a member of the list for each column in the table. If the table has five columns, the TblColWidth list will contain five members.
The key to the script is to loop through the list of measurements, multiply each one by vScaleFactor and put the new value back in the list.
// Loop through the list and calculate each
// table column's new width.
Loop While(vCounter <= vWidths.Count) LoopVar(vCounter)
Get Member Number(vCounter) From(vWidths) NewVar(vWidth);
Set vNewWidth = vWidth * vScaleFactor;
Replace Member Number(vCounter) In(vWidths) With(vNewWidth);
The vCounter variable will increment by 1 (Incr(1)) starting at 1 (Init(1)) through the number of members in vWidths (vWidths.Count). Each member will be multiplied by the scale factor, and the member will be replaced with the new value.
Your vWidths MetricList variable now contains the correct widths to scale the table to the column width. The only thing left to do is assign the new values to the table.
Set vTbl.TblColWidths = vWidths;