How to Append an Existing Excel File in Visual Basic
- 1). Include the Visual Basic libraries that contain the functions and properties used for Excel manipulation. Place the following code at the top of your Visual Basic file:
Imports Microsoft.Office.Interop
Imports System.Runtime.InteropServices - 2). Initialize the Excel object and assign it to a variable. Initializing the object allows you to open a file on your desktop. The following code creates an Excel object variable:
Dim excel As New Excel.Application() - 3). Open your existing file. The following code opens the Excel spreadsheet, so you can append information:
excel.Workbooks.Open("c:\myExcelFile.xls")
Dim sheet As Excel.Worksheet = excel.Worksheets("Sheet1") - 4). Find the range of cells that is already filled with data and add one to the cell range. The "UsedRange" property finds all the rows that already have information entered. Adding one to the range points the next available cell to the next row. The following code gets your next row for data entry:
Dim nextRow As Integer = sheet.UsedRange.End(Excel.XlDirection.xlDown).Row + 1 - 5). Enter data into the next available row using the "nextRow" variable created in Step 4. The following code appends data to the Excel spreadsheet:
sheet.Cells(nextRow, 1) = "New Row Data" - 6). Save the spreadsheet and close the Excel application. The following code finalizes the changes to your spreadsheet and closes the file:
sheet.Save()
excel.Quit()