Search code examples
excelvb.netoffice-automation

Opening an excel file using VB.Net


I am getting an error Object reference not set to an instance of an object when I write the following code in the line owb = oxl.Workbooks.Open("G:\NTPC.xlsx"). There is no problem with the file and it indeed exists in the G drive of my pc. Pls tell where I am going wrong?

Imports System
Imports Microsoft.Office.Interop
Module Program

    Dim oxl As Excel.Application
    Dim owbs As Excel.Workbooks
    Dim owb As Excel.Workbook
    Dim osheets As Excel.Worksheets
    Dim osheet As Excel.Worksheet

    Sub Main(args As String())
        'oxl = CreateObject("Excel.Application")
        'oxl.DisplayAlerts = True
        'oxl.Visible = True
        owb = oxl.Workbooks.Open("G:\NTPC.xlsx")
    End Sub
End Module

Solution

  • You need to create an Excel Application instance in the code first.

    Imports System
    Imports Microsoft.Office.Interop
    Module Program
    
        Dim oxl As Excel.Application
        Dim owbs As Excel.Workbooks
        Dim owb As Excel.Workbook
        Dim osheets As Excel.Worksheets
        Dim osheet As Excel.Worksheet
    
        Sub Main(args As String())
            oxl = CreateObject("Excel.Application")
            'oxl.DisplayAlerts = True
            oxl.Visible = True
            owb = oxl.Workbooks.Open("G:\NTPC.xlsx")
        End Sub
    End Module