Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
workbook = APP.Workbooks.Open("C:\Users\act08\Copy of Copy of test1.xlsx")
worksheet = workbook.Sheets.Item(1)
'each textbox input to excel
worksheet.Cells(1, 1).Value = TextBox1.Text
worksheet.Cells(1, 2).Value = TextBox2.Text
worksheet.Cells(2, 1).Value = TextBox3.Text
'save the input
workbook.Close(SaveChanges:=True)
APP.Quit()
End Sub
-
Which line of code is the error on? I don't see where you are creating new instances of anything.David.Warwick– David.Warwick2021-12-02 03:03:47 +00:00Commented Dec 2, 2021 at 3:03
-
Does this answer your question? What is a NullReferenceException, and how do I fix it?It all makes cents– It all makes cents2021-12-02 03:20:53 +00:00Commented Dec 2, 2021 at 3:20
-
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.Community– Community Bot2021-12-07 05:43:42 +00:00Commented Dec 7, 2021 at 5:43
Add a comment
|
1 Answer
Without the casting, your variables end up as Object which does not have the properties and methods you are expecting from the Excel objects.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim APP As New Excel.Application
Dim workbook = DirectCast(APP.Workbooks.Open("C:\Users\act08\Copy of Copy of test1.xlsx"), Excel.Workbook)
Dim worksheet = DirectCast(workbook.Sheets.Item(1), Excel.Worksheet)
'each textbox input to excel
Dim cell = DirectCast(worksheet.Cells(1, 1), Excel.Range)
cell.Value = TextBox1.Text
Dim cell2 = DirectCast(worksheet.Cells(1, 2), Excel.Range)
cell2.Value = TextBox2.Text
Dim cell3 = DirectCast(worksheet.Cells(2, 1), Excel.Range)
cell3.Value = TextBox3.Text
'save the input
workbook.Close(SaveChanges:=True)
APP.Quit()
End Sub
1 Comment
Craig
While this is generally good advice, I wouldn't expect a NullReferenceException to arise from not following it.