[英]Excel VBA Vlookup Runtime Error 1004
我正在嘗試創建一個函數,該函數將運行一個循環,該循環進行測試以查看組織(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檢查結果。
我還對代碼進行了一些改進,因為它現在可以隨機選擇任何有效的廣告系列。 在此之前,只需選擇它找到的第一個有效廣告系列即可。
那些敏銳的眼睛可能還會注意到,我在更新版本中引用的工作表與原始代碼中的工作表不同。 原始工作表是錯誤的,我引用的是我從中調用模塊的同一工作表,以循環引用結尾。 這個微小的差異使我在幾個小時的頭發撕裂困惑中喪生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.