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
Asked
Active
Viewed 115 times
0
-
Which line of code is the error on? I don't see where you are creating new instances of anything. – David.Warwick Dec 02 '21 at 03:03
-
Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Tu deschizi eu inchid Dec 02 '21 at 03: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 Dec 07 '21 at 05:43
1 Answers
1
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

Mary
- 14,926
- 3
- 18
- 27
-
1While this is generally good advice, I wouldn't expect a NullReferenceException to arise from not following it. – Craig Dec 02 '21 at 14:16