Object reference not set to an instance of an object error when trying to add a new column to an excel spreadsheet
Hi, I was hoping someone would be able to offer me some assistance please? My excel worksheet contains various columns, what I was hoping to do is simply just add another column at the end.
Now I have managed to get the column letter however when I try to add text into the header row I get an error of Object reference not set to an instance of an object on the line in bold
My coding
Any help is greatly appreciated, many thanks
Hi, I was hoping someone would be able to offer me some assistance please? My excel worksheet contains various columns, what I was hoping to do is simply just add another column at the end.
Now I have managed to get the column letter however when I try to add text into the header row I get an error of Object reference not set to an instance of an object on the line in bold
My coding
Any help is greatly appreciated, many thanks
Code:
Dim xls As New Excel.Application
Dim xWorkbook As Excel.Workbook
Dim xWorksheet As Excel.Worksheet
Dim lColumn As Long = 0
xWorkbook = xls.Workbooks.Open("D:\Test.xlsx") 'File Location
xWorksheet = xWorkbook.Sheets(1)
xls.Visible = True
With xWorksheet
If xls.WorksheetFunction.CountA(.Columns) <> 0 Then
lColumn = .Columns.Find(What:="*", _
After:=.Range("A1"), _
LookAt:=Excel.XlLookAt.xlPart, _
LookIn:=Excel.XlFindLookIn.xlFormulas, _
SearchOrder:=Excel.XlSearchOrder.xlByColumns, _
SearchDirection:=Excel.XlSearchDirection.xlPrevious, _
MatchCase:=False).Column
Else
lColumn = 1
End If
End With
With xWorksheet
.Range(ColumnIndexToColumnLetter(lColumn + 1) & 1).Value = "TESTT"
End With
Private Function ColumnIndexToColumnLetter(colIndex As Integer) As String
Dim div As Integer = colIndex
Dim colLetter As String = String.Empty
Dim modnum As Integer = 0
While div > 0
modnum = (div - 1) Mod 26
colLetter = Chr(65 + modnum) & colLetter
div = CInt((div - modnum) \ 26)
End While
Return colLetter
End Function