2014-01-07 238 views
0

我试图创建一个函数,它将运行一个循环来测试一个组织(var'org')是否有一个实际上已经启动的活动,因此'If(结果< = Now()'。我在电子表格中找到了数量未指定的广告系列,并使用'CountIf'并将其作为“总计”提供给模块。Excel VBA Vlookup运行时错误1004

在电子表格中,当需要的单元格有效的广告系列发现广告系列在另一个单元格中随机猜测出的广告系列无效,因此会转到VBA功能,并为该组织标识以及该广告系列下的广告系列总数提供功能。

我的代码:

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作物并在电子表格中执行时,该功能似乎什么也不做,细胞很快刷新细胞之前采用最后的有效值。 我该如何解决这个问题?

+0

尝试将结果的类型从范围更改为变体。 VLookup()返回值(字符串,双精度)或错误类型。 – Makah

+0

这已被覆盖很多次:) –

+0

[这里](http://stackoverflow.com/questions/20593959/using-vlookup-from-a-vba-module-in-excel-to-check-if-value -is-in-table)就是一个例子... [另一个](http://stackoverflow.com/questions/19057369/vlookup-in-vba-within-a-for-loop)...和[另一个ONE](http://stackoverflow.com/questions/9634611/unable-to-get-the-lookup-property-of-the-worksheetfunction-class)在同一行上... –

回答

1

因此,对于那些谁可以跨越这个后绊倒,这是我的工作代码:

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 

基本上,“上的错误继续下一步”固定的问题。然后我添加了If IsNull检查结果。

我也稍微改进了代码,因为它现在随机选择任何一个有效的广告系列。在它只是选择它找到的第一个有效的广告系列之前。

那些敏锐的眼睛也许会注意到,我在更新版本中引用的工作表与我原始代码中的不同。原始表单是错误的,我引用了我调用该模块的同一张表单,以循环引用结尾。这一小小的差异让我头痛几个小时,导致了混乱。