0

I wrote the function below. However, when handling the status variable, I get an error NullReference Exception unhandled by user code.

I come from VBA where I did not have to deal with this type of issue on my functions. the status variable is supposed to set my objects properties to true or false.

I tried setting

status = New Boolean
status = False

But nothing worked

Here is my code

    Option Strict On
    Option Explicit On

    Imports Microsoft.Office.Interop.Excel
    Imports System.Windows.Forms

    Module sheetView

    Function viewSheets(sheetName As String, status As Boolean) As String

        Dim ThisApplication As Excel.Application = New Excel.Application()
        Dim WB As Excel._Workbook
        Dim WS As Excel.Worksheet


        WB = CType(Globals.ThisWorkbook.Application.ActiveWorkbook, Excel.Workbook)
        WS = CType(WB.Sheets(sheetName), Excel.Worksheet)

        With ThisApplication

            .ScreenUpdating = False

            WS.Select()

            .ActiveWindow.DisplayGridlines = status
            .ActiveWindow.DisplayHeadings = status
            .ActiveWindow.DisplayWorkbookTabs = status
            .DisplayFormulaBar = status
            .DisplayStatusBar = status
            .ExecuteExcel4Macro("Show.ToolBar(""Ribbon"", status)")


            .ScreenUpdating = True


        End With

        Return ""

    End Function

    End Module


    Private Sub btnEmployeeDashboard_Click(sender As Object, e As EventArgs) Handles btnEmployeeDashboard.Click

    sheetView.viewSheets("employeeBoard", True)

End Sub
2
  • 2
    Are you sure that the status variable is where the problem is? Do you know on which line the error is happening? Is there a reason you are declaring WB as a _Workbook but casting Globals.ThisWorkbook.Application.ActiveWorkbook to a Workbook (no underscore)? Commented Jul 6, 2013 at 15:42
  • The status variable is assigning to a null reference, so @JLRishe is right, hard to say where its failing without stepping through a debugger, can you post the stack trace? Commented Jul 6, 2013 at 16:04

1 Answer 1

1

A NullReference occurs when you try to access a class member when there is no object instance.

In other words: one of the values (ThisApplication/ WB / WS / WS.ActiveWindow) is empty. Step through your code in the debugger to find out which one.

Sign up to request clarification or add additional context in comments.

Comments

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.