在Function中处理NullReference异常

时间:2013-07-06 15:37:27

标签: vb.net

我写下了这个功能。但是,在处理状态变量时,我收到一个错误NullReference Exception,未被用户代码处理。

我来自VBA,我没有必要在我的职能上处理这类问题。 status变量应该将我的对象属性设置为true或false。

我尝试过设置

status = New Boolean
status = False

但没有任何效果

这是我的代码

    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

1 个答案:

答案 0 :(得分:1)

当您在没有对象实例时尝试访问类成员时,会发生NullReference

换句话说:其中一个值(ThisApplication / WB / WS / WS.ActiveWindow)为空。在调试器中逐步执行代码以找出哪一个。