0
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
3
  • Which line of code is the error on? I don't see where you are creating new instances of anything. Commented Dec 2, 2021 at 3:03
  • Does this answer your question? What is a NullReferenceException, and how do I fix it? Commented 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. Commented Dec 7, 2021 at 5:43

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

While this is generally good advice, I wouldn't expect a NullReferenceException to arise from not following it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.