As Brady said already, if you can forgo the 'formula' aspect (which allows you to append new rows and get results automatically), the matrix approach scales much better.
But if you did want to dynamically create the formula columns, it would look something like this:
NamesDefaultToHere(1);
// Table with six source columns
dt = New Table( "Sum of Columns",
New Column( "Column 1", Numeric, "Continuous", Format( "Fixed Dec", 10, 3 ), Formula( Random Normal( 0, 1 ) ) ),
New Column( "Column 2", Numeric, "Continuous", Format( "Fixed Dec", 10, 3 ), Formula( Random Normal( 0, 1 ) ) ),
New Column( "Column 3", Numeric, "Continuous", Format( "Fixed Dec", 10, 3 ), Formula( Random Normal( 0, 1 ) ) ),
New Column( "Column 4", Numeric, "Continuous", Format( "Fixed Dec", 10, 3 ), Formula( Random Normal( 0, 1 ) ) ),
New Column( "Column 5", Numeric, "Continuous", Format( "Fixed Dec", 10, 3 ), Formula( Random Normal( 0, 1 ) ) ),
New Column( "Column 6", Numeric, "Continuous", Format( "Fixed Dec", 10, 3 ), Formula( Random Normal( 0, 1 ) ) ),
AddRows( 10 )
);
// List of columns (can be any number of columns!)
cList = dt << getColumnNames;
// Build the 'negative sum' formula expression
colContribution = Expr(colTBD * If( colTBD < 0, 1, 0 ));
formArg = Expr(Add());
For(c=1, c<=NItems(cList), c++,
thisColContribution = NameExpr(Substitute(NameExpr(colContribution), Expr(colTBD), EvalExpr(AsColumn(cList[c]))));
InsertInto(formArg, thisColContribution);
);
nsExpr = Expr(Formula(fTBD));
SubstituteInto(nsExpr, Expr(fTBD), NameExpr(formArg));
// Print(nsExpr);
// Build the 'positive sum' formula expression
colContribution = Expr(colTBD * If( colTBD >= 0, 1, 0 ));
formArg = Expr(Add());
For(c=1, c<=NItems(cList), c++,
thisColContribution = NameExpr(Substitute(NameExpr(colContribution), Expr(colTBD), EvalExpr(AsColumn(cList[c]))));
InsertInto(formArg, thisColContribution);
);
psExpr = Expr(Formula(fTBD));
SubstituteInto(psExpr, Expr(fTBD), NameExpr(formArg));
// Print(psExpr);
// Add the two formula columns to dt
nsCol = dt << NewColumn("Sum of Negatives", Numeric, Continuous, Format( "Fixed Dec", 10, 3 ));
makeFormula = Expr(Send(nsCol));
InsertInto(makeFormula, NameExpr(nsExpr));
makeFormula;
psCol = dt << NewColumn("Sum of Positives", Numeric, Continuous, Format( "Fixed Dec", 10, 3 ));
makeFormula = Expr(Send(psCol));
InsertInto(makeFormula, NameExpr(psExpr));
makeFormula;