0

I have a simple VB.NET routing to open a text file into Excel and then save it as a Excel file (.xlsx). The open works file but saving fails with the NullReference Exception.

 FileName = "C:\Temp\BOM of " & AssyName & ".txt"
    Dim xlApp As New Excel.Application
    Dim xlWorkBook As Excel.Workbook = Nothing
    Dim xlWorkSheet As Excel.Worksheet


    xlApp.Workbooks.OpenText(FileName, _
       StartRow:=1, _
       DataType:=Excel.XlTextParsingType.xlDelimited, _
       TextQualifier:=Excel.XlTextQualifier.xlTextQualifierNone, _
       Comma:=True)
    xlApp.Visible = True

    xlWorkBook.SaveAs("C:\Temp\BOM of " & AssyName & ".xlsx", Excel.XlFileFormat.xlWorkbookNormal)
    xlWorkBook.Close(True)
    xlApp.Quit()

Not sure what is going here. Image has failure message.

Thanks.VB>NET Failure on saving an Excel file.

CodeWriter
  • 71
  • 1
  • 13
  • 1
    Possible duplicate of [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) – TnTinMn Apr 19 '18 at 22:17

1 Answers1

0

Looks like Dim xlWorkBook As Excel.Workbook = Nothing is the logical cause.

In the incomplete code you posted, you do not set xlWorkbook to anything. So when you go to save, xlWorkbook is literally Nothing.

Not tested, but consider:

xlWorkBook = xlApp.Workbooks.OpenText(FileName, _
       StartRow:=1, _
       DataType:=Excel.XlTextParsingType.xlDelimited, _
       TextQualifier:=Excel.XlTextQualifier.xlTextQualifierNone, _
       Comma:=True)
AJD
  • 2,400
  • 2
  • 12
  • 22