I would like to make a VBSript that will open a csv of varying rows and columns and paste them starting at row 4 column 1. So far what I have written is slow and has the amount of columns hard coded into it.
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open(wscript.Arguments(0))
objExcel.Visible = True
objExcel.Cells(1, 4).Value = wscript.Arguments(1)+" - "+wscript.Arguments(2)
objExcel.Cells(2, 4).Value = wscript.Arguments(3)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile (wscript.Arguments(4))
cCount = 1
rCount = 4
Do While objTextFile.AtEndOfStream <> True
arrUserRecord = split(objTextFile.Readline, ",")
Do While cCount<213
objExcel.Cells(rCount, cCount).Value = arrUserRecord(cCount-1)
cCount=cCount+1
Loop
cCount=1
rCount=1+rCount
Loop
Excel can be rather particular about what it accepts as "valid CSV". I had to resort to the following on several occasions:
Const vbFormatStandard = 1
Const vbFormatText = 2
Const vbFormatDate = 4
Const xlDelimited = 1
Const xlDoubleQuote = 1
' change according to number/type of the fields in your CSV
dataTypes = Array( Array(1, vbFormatText) _
, Array(2, vbFormatStandard) _
, Array(3, vbFormatText) _
, Array(4, vbFormatDate) _
)
Set xl = CreateObject("Excel.Application")
xl.Visible = True
xl.Workbooks.OpenText "input.csv", , , xlDelimited, xlDoubleQuote, False _
, False, True, , , , dataTypes
Set wb = xl.ActiveWorkbook
If its a valid CSV file, then Excel can open it directly. So just write your VBscript to tell Excel to open the CSV file as though it was a workbook. Then you can copy the data you want from that workbook into your workbook.
If you don't know how to do this, then VBA is the best way, but you should be able to mock it up in VBscript as well. Here is what I think it should look like, though I cannot test to be sure:
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open(wscript.Arguments(0))
objExcel.Visible = True
objExcel.Cells(1, 4).Value = wscript.Arguments(1) + " - " + wscript.Arguments(2)
objExcel.Cells(2, 4).Value = wscript.Arguments(3)
Set objWorksheet = objWorkbook.ActiveSheet
Set objWbkCsv = objExcel.Workbooks.Open(wscript.Arguments(4))
Set objWksCsv = objWbkCsv.Worksheets(1)
Set objRangeSource = objWksCsv.UsedRange
cCount = objRangeSource.Columns.Count
rCount = objRangeSource.Rows.Count + (4 - 1)
Set objRangeDest = objWorksheet.Range(objWorksheet.Cells(4, 1), objWorksheet.Cells(rCount, cCount))
objRangeSource.Copy objRangeDest