Friday, April 9, 2010

VBScript - How Can I Cut a Row From One Office Excel Spreadsheet and Paste That Row Into Another Spreadsheet?

VBScript - How Can I Cut a Row From One Office Excel Spreadsheet and Paste That Row Into Another Spreadsheet?

Const xlDown = -4121

'Open first spreadsheet
Set objOldExcel = CreateObject("Excel.Application")
objOldExcel.Visible = True

Set objOldWorkbook = objOldExcel.Workbooks.Open("C:\Scripts\OldTest.xls")
Set objOldWorksheet = objOldWorkbook.Worksheets("Sheet1")

'Open second spreadsheet
Set objNewExcel = CreateObject("Excel.Application")
objNewExcel.Visible = True

Set objNewWorkbook = objNewExcel.Workbooks.Open("C:\Scripts\NewTest.xls")
Set objNewWorksheet = objNewWorkbook.Worksheets("Sheet1")

'Cut row from the original spreadsheet
Set objOldRange = objOldWorksheet.Range("A1").EntireRow
objOldRange.Cut

'Find the first unused row in the second spreadsheet

Set objNewRange = objNewExcel.Range("A1")
objNewRange.End(xlDown).Activate
intNewRow = objNewExcel.ActiveCell.Row + 1
strNewCell = "A" & intNewRow
objNewExcel.Range(strNewCell).Activate

'Paste the data into the second spreadsheet
objNewWorksheet.Paste

'Delete the row from the original spreadsheet
objOldRange.Delete

[Via]