我正在尝试创建一个在subs中使用的函数,它创建一个月内实际日期的数组。我无法直接使用立即窗口或使用子命令来运行该功能。该函数的代码如下(Debug.Print
实例被删除,因为它们从未触发过):
Function GenererDager(ByVal month As Integer, ByVal year As Integer) As Integer
Dim dateFormat As String, daysArr() As Integer, actualDays As Integer
actualDays = 1
' Find the number of actual days in given month
For dayCheck = 1 To 31
dateFormat = month & "/" & dayCheck & "/" & year ' mm/dd/yyyy format
If IsDate(dateFormat) Then
actualDays = actualDays + 1
Else
Exit For
End If
Next dayCheck
' Redimension the array with the actual number of days in the month
ReDim daysArr(actualDays)
' Populate the array with the correct number of days
For daysToArray = 1 To actualDays
daysArr(daysToArray) = daysToArray
Next daysToArray
GenererDager = daysArr
End Function
使用带GenererDager(2, 2017)
的立即窗口运行该函数会产生以下错误消息:Compile error: Expected: =
使用带有?GenererDager(2, 2017)
的立即窗口运行该函数会产生以下错误消息:Compiler error: Type mismatch
,其中选择了最后一次使用daysArr
我用来调用函数的test-sub看起来像这样:
Sub HentDager()
Dim daysArray() As Integer
daysArray = GenererDager(2, 2017)
Debug.Print daysArray(4)
End Sub
使用HentDager()
在即时窗口中调用此子句会产生以下错误:Compile error: Expected: =
我已经暂时停留在这个问题上一段时间了,我已经多次重写代码来识别问题,但到目前为止我一直无法解决它。我可能产生了比我在过程中修复的错误更多的错误,因为我已经意识到我不知道我现在正在做什么: - )
答案 0 :(得分:3)
您必须声明对象并将其作为Variant函数来传递数组。
此外,您的功能需要进行一些更改:
actualDays = actualDays - 1
因为您返回的第一个值不是日期!ReDim daysArr(1 To actualDays)
以避免在数组的第一个索引上有空值,daysArr(0)
工作职能(已测试):
Function GenererDager(ByVal month As Integer, ByVal year As Integer) As Variant
Dim dateFormat As String, daysArr() As Variant, actualDays As Integer, dayCheck As Integer, daysToArray As Integer
actualDays = 1
' Find the number of actual days in given month
For dayCheck = 1 To 31
dateFormat = month & "/" & dayCheck & "/" & year ' mm/dd/yyyy format
If IsDate(dateFormat) Then
actualDays = actualDays + 1
Else
Exit For
End If
Next dayCheck
actualDays = actualDays - 1
' Redimension the array with the actual number of days in the month
ReDim daysArr(1 To actualDays)
' Populate the array with the correct number of days
For daysToArray = 1 To actualDays
daysArr(daysToArray) = daysToArray
Next daysToArray
GenererDager = daysArr
End Function
测试:
Sub HentDager()
Dim daysArray() As Variant
daysArray = GenererDager(2, 2017)
'Display last day of the month in the immediate window
Debug.Print daysArray(UBound(daysArray))
End Sub
经过一些试验和错误后,这是一个使用Integer
的示例:
Sub TestIntSub()
Dim TestInt() As Integer
TestInt = FctIntArr
Debug.Print TestInt(1) & "|" & TestInt(2)
End Sub
Public Function FctIntArr() As Integer()
Dim IntArr() As Integer
ReDim IntArr(1 To 2)
IntArr(1) = 545
IntArr(2) = 232
FctIntArr = IntArr
End Function
答案 1 :(得分:2)
您需要正确定义函数的返回类型 -
Function GenererDager(ByVal month As Integer, ByVal year As Integer) As Integer
将其更改为
Function GenererDager(ByVal month As Integer, ByVal year As Integer) As Variant
答案 2 :(得分:1)
函数的返回值实际上是整数而不是整数()
而不是将daysarray调暗为数组只是将其调暗为变量并指定值