Home » excel » Excel VBScript insert column and fill

Excel VBScript insert column and fill

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to insert a column to an Excel spreadsheet via a script. I found the code below which should allow me to insert a column, but how would I then go about filling that column with data like I would in the Excel application using the fill>down or fill>series commands?

Const xlToRight = -4161
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWB = objExcel.Workbooks.Open("C:\Temp\Scripts\Test2.xls")
Set objSheet = objwb.Sheets("Overall")
objSheet.Columns("D:D").Insert xlToRight
objWB.Close True
objExcel.Quit

EDIT

Here’s what ended up working.

Const xlToRight = -4161
const xlColumns = &H2 
const xlLinear = -4132 
const xlDay = 1
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWB = objExcel.Workbooks.Open("C:\Temp\Scripts\Test2.xls")
Set objSheet = objwb.Sheets("Overall")
objSheet.Columns("A:A").Insert xlToRight
objSheet.Cells(1, 1).Value = "label"
objSheet.Cells(2, 1).Value = "Value"
set Range = objSheet.Range("A2:A"&objSheet.UsedRange.Rows.Count) 
Range.FillDown
objSheet.Columns("A:A").Insert xlToRight
objSheet.Cells(1, 1).Value = "series"
objSheet.Cells(2, 1).Value = 1
set Range = objSheet.Range("A2:A"&objSheet.UsedRange.Rows.Count) 
Range.DataSeries xlColumns, xlLinear,xlDay, 1, , False
objWB.Close True
objExcel.Quit
How to&Answers:

How To Insert a value into a Cell

The syntax (the object model) of using vbscript seems to be quite similar to excel VBA Macros.

objSheet.Cells(2,4).Value = "foo"

If you have any trouble finding something out it may work to create an excel macro using the built in macro recorder and take a look at the generated vba code – this helped me in the past to better understand excel vba macros. I assume that the vba code can be used in vbscript as well.