2014-06-10 71 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財產,如果對象是不存在的。