我是VBA的新手,而且我真的把头发撕成了这个。 我正在使用Excel宏,每当我尝试创建一个Type时,我都无法从函数中访问它。我已经从其他地方在线复制并粘贴了类似的示例并得到了相同的错误(未定义用户定义的类型)。我看到其他人也有类似的错误,但没有一个解决方案似乎适用于这个特定的问题。这是(简化)代码:
Type ScheduleDate
Public Resident As String
Public SDate As Date
Public Activity As String
End Type
Sub Generate_Schedule()
Dim Sched As ScheduleDate
End Sub
提前致谢!
MTA:我想出来了!当我在这里复制并粘贴它时,我遗漏了一个我放在Type上面的函数。显然,VBA不允许在类型之前使用函数。我想,总是存在简化的风险。谢谢你的帮助!
答案 0 :(得分:2)
你喜欢这样的事情:
Option Explicit
Public Type ScheduleDate
Resident As String
SDate As Date
Activity As String
End Type
Sub Generate_Schedule()
Dim Sched As ScheduleDate
Sched.Resident = "The resident"
Sched.SDate = #11/16/2015#
Sched.Activity = "My activity"
End Sub
此外,如果您尝试对变量进行分组,我建议您创建一个类。每次我使用类型时,我最终都会将其更改为类。请看下面的一个例子。
在常规模块中:
Option Explicit
Sub Generate_Schedule()
Dim Sched As New clsSchedule
Sched.Resident = "The resident"
Sched.ScheduleDate = #11/16/2015#
Sched.Activity = "My activity"
End Sub
现在在名为“clsSchedule”的类模块中:
Option Explicit
Private m_strResident As String
Private m_dtmScheduleDate As Date
Private m_strActivity As String
' -------------------------------
' Property Resident
' -------------------------------
Public Property Get Resident() As String
Resident = m_strResident
End Property
Public Property Let Resident(ByVal strResident As String)
m_strResident = strResident
End Property
' -------------------------------
' Property ScheduleDate
' -------------------------------
Public Property Get ScheduleDate() As Date
ScheduleDate = m_dtmScheduleDate
End Property
Public Property Let ScheduleDate(ByVal dtmScheduleDate As Date)
m_dtmScheduleDate = dtmScheduleDate
End Property
' -------------------------------
' Property Activity
' -------------------------------
Public Property Get Activity() As String
Activity = m_strActivity
End Property
Public Property Let Activity(ByVal strActivity As String)
m_strActivity = strActivity
End Property
我知道这似乎是更多的代码,但一切都很好。 希望这可以帮助。
答案 1 :(得分:0)
声明整个类型的范围,而不是单个属性:
Public Type ScheduleDate
Resident As String
SDate As Date
Activity As String
End Type
Sub Generate_Schedule()
Dim Sched As ScheduleDate
End Sub