我主要是一名C ++ / C#程序员,对VBA非常不熟悉,所以我不太确定这段代码到底是什么问题。它引发了以下错误:
“运行时错误'91':对象变量或未设置块变量。”
在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
答案 0 :(得分: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#中使用任何类似的语法。
答案 1 :(得分:1)
ReDim gEmployees(0 To iNameCount - 1)
只创建一个包含iNameCount
个插槽的空数组 - 您尚未使用Employee
对象填充每个插槽,因此如果有mLastName
属性,则无法设置{{1}}属性对象不在那里。