我正在尝试创建一个函数,该函数将运行一个循环,该循环进行测试以查看组织(var'org')是否有实际上已经开始的活动,因此为'If(result <= Now()'。是我在电子表格中使用“ CountIf”找到的未指定数量的广告系列,并以“总计”的形式提供给模块。
在电子表格中,当需要有效广告系列的单元格发现在另一个单元格中随机猜测的广告系列无效时,它将转到VBA功能,为该功能提供组织ID和该组织下的广告系列总数。
我的代码:
Sub Macro()
Dim x
x = MacIDGen(111, 11)
End Sub
Function MacIDGen(org, total)
Dim iteration As Boolean, result As Range
For current = 1 To total
result = Application.WorksheetFunction.VLookup(org & " " & current, ActiveWorkbook.Sheets("Donations").Range("C:E"), 3, False)
If (result <= Now()) Then
MacIDGen = org & " " & current & " Test successful"
current = total
End If
Next current
End Function
电子表格结构:
Org ID- Org Camp Count- Camp No.- Valid Camp No.
62 1 1 62 1
14 2 1 14 1
2 4 4 2 4
79 5 4 79 4
在VBA编辑器中进行调试期间,runtime error 1004
突然出现,在电子表格中执行该函数时,似乎没有执行任何操作,并且该单元格采用了最后一个有效值,然后才快速刷新单元格。我怎样才能解决这个问题?
因此,对于那些以后可能会迷失方向的人来说,这是我的工作代码:
Function MacIDGen2(org As Integer, total As Integer)
Dim iteration As Boolean, trueArray() As String, totalTrue As String, randArrNo As Integer, result
ReDim trueArray(total)
totalTrue = 0
For current = 0 To total - 1
On Error Resume Next
result = Application.WorksheetFunction.VLookup(org & " " & current + 1, ActiveWorkbook.Sheets("Campains").Range("C:E"), 3, False)
On Error GoTo 0
If (Not IsNull(result)) Then
If (result <= Now()) Then
trueArray(totalTrue) = current + 1
totalTrue = totalTrue + 1
End If
End If
Next current
If (totalTrue > 0) Then
randArrNo = WorksheetFunction.RandBetween(0, totalTrue - 1)
MacIDGen2 = org & " " & trueArray(randArrNo)
Else
MacIDGen2 = 0
End If
End Function
基本上,“ On Error Resume Next”解决了该问题。然后我添加了If IsNull检查结果。
我还对代码进行了一些改进,因为它现在可以随机选择任何一个有效的广告系列。在此之前,只需选择它找到的第一个有效广告系列即可。
那些敏锐的眼睛可能还会注意到,我在更新版本中引用的工作表与原始代码中的工作表不同。原始工作表是错误的,我引用的是我从中调用模块的同一工作表,以循环引用结尾。这种微小的差异使我在几个小时的头发撕裂困惑上花费了我很多时间。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句