Friday, April 2, 2010

VBScript - Wrapping Text in an Excel Spreadsheet

VBScript - Wrapping Text in an Excel Spreadsheet

Here's a script that uses the UsedRange property to select the portion of the worksheet that actually contains data. With the used portion of the worksheet selected we then set the vertical alignment of all the cells in the range to the top of the cell:

Const xlVAlignTop = -4160

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
Set objWorksheet = objWorkbook.Worksheets(1)

Set objRange = objExcel.Range("B1").EntireColumn
objRange.WrapText = TRUE

objExcel.Cells(1, 1).Value = "A"
objExcel.Cells(1, 2).Value = "This is the text that we want to wrap in column B."
objExcel.Cells(1, 3).Value = "C"
objExcel.Cells(1, 4).Value = "D"

Set objRange2 = objWorksheet.UsedRange
objRange2.VerticalAlignment = xlVAlignTop

[Via]