简体   繁体   中英

saveAs for Excel file not working in VB.NET

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM