2014-06-10 70 views
0

我主要是C++/C#程序员,对VBA非常不熟悉,所以我不太确定这个代码到底是什么问题。它抛出以下错误:对象变量未设置错误?

"Run-time error '91': Object variable or With block variable not set."

该错误正在FOR循环中的行被抛出。声明的右侧似乎在抛出错误。这条线的问题到底是什么,我该如何解决它?

下面的代码片断:

Option Explicit 

Private gEmployees() As Employee 

Const gLastNameStartingCell = "A4" 
Const gNamesCountCell = "A1" 

Const gNamesTab = "NamesTab" 

Function BuildEmployeeNameArray() 

    ' Declare all variables 
    Dim iNameCount As Integer 
    Dim wksActive As Object 

    ' Counter 
    Dim i As Integer 

    ' Select the sheet with all the names 
    Set wksActive = Sheets(gNamesTab) 

    ' Get the number of names on the sheet 
    iNameCount = wksActive.Range(gNamesCountCell) 

    ' Resize the Array as appropriate 
    ReDim gEmployees(0 To iNameCount - 1) 

    ' Fill out the employee list 
    For i = 0 To iNameCount - 1 
     gEmployees(i).mLastName = wksActive.Range(gLastNameStartingCell).Offset(i, 0).Value 
    Next i 

End Function 

雇员是一个类模块。以下是该文件中的相关信息。

Option Explicit 
Public mLastName As String 

Private Sub Class_Initialize() 

    ' Initialize variables 
    mLastName = "" 

End Sub 

回答

2

您错过了要添加到阵列的实际员工的创建。

Dim e as Employee 
' Fill out the employee list 
For i = 0 To iNameCount - 1 
    'Create a new employee each time through the loop 
    set e = new employee 
    gEmployees(i)=e 

    'set the last name appropriately 
    gEmployees(i).mLastName = wksActive.Range(gLastNameStartingCell).Offset(i, 0).Value 
Next i 

这将解决您的问题。

该数组从未设置类型,或者您正在执行此操作的方式,所以我不确定您将如何获得任何类似的语法以在C++/C#中工作。

+0

啊,那个“set”就是我想念的东西......我试图在出于习惯之前在同一个地方使用新的东西,但它也抛出了一个错误。这实际上是被投入到任何形式的虚拟基础设施中的第一天,所以我在黑暗中感觉有点。 – Ishnatal

1
ReDim gEmployees(0 To iNameCount - 1) 

只是创建了iNameCount插槽空数组 - 没有填充每个那些插槽与Employee对象,所以你不能设置mLastName财产,如果对象是不存在的。