我遇到過這種情況,需要我平均Vlookups數組的結果。我不知道如何用公式來實現這一點,並且似乎StackOverflow上的其他人也沒有任何想法。用戶定義函數返回#值I2
所以我決定寫一個函數來爲我完成這個工作。不幸的是它返回「#VALUE!」錯誤,我不知道爲什麼!該功能在使用msgbox進行測試時工作正常。我有以下注釋我的代碼:
Option Explicit
Public Function AvgVlookup(Target_Array As String, Lookup_Array As String, Column_Index As Long) As Double
Dim Result As Double
Dim Total As Double
Dim Counter As Long
Dim TargetRange As Range
Dim LookupRange As Range
Dim Cell As Range
' Remove Absolute Indicator
Target_Array = Replace(Target_Array, "$", "")
Lookup_Array = Replace(Lookup_Array, "$", "")
' Convert String to Range
Set TargetRange = Range(Left(Target_Array, InStr(1, Target_Array, ":") - 1), Mid(Target_Array, InStr(1, Target_Array, ":") + 1))
Set LookupRange = Range(Left(Lookup_Array, InStr(1, Lookup_Array, ":") - 1), Mid(Lookup_Array, InStr(1, Lookup_Array, ":") + 1))
' Set Variables to 0
Counter = 0
Total = 0
' For each cell in defined array
For Each Cell In TargetRange
' Vlookup the cell and save lookup value to Result variable
Result = Application.WorksheetFunction.vlookup(Cell, LookupRange, Column_Index, "False")
' Update variables used to calculate average
Total = Total + Result
Counter = Counter + 1
Next Cell
' Perform calculation
AvgVlookup = Total/Counter
End Function
Sub test()
MsgBox AvgVlookup("A5:A8", "G5:H8", 2)
End Sub
任何想法?
謝謝!
有你放置一個破線的功能,並通過它踩線,由線在錯誤發生時通過向excactly評價? –
嗨斯科特。代碼本身沒有錯誤。我可以通過測試子來運行它,它會將我想要的結果返回到msgbox。它只是在我出於某種原因輸入它的單元格中返回這個錯誤。 – JaayB
*代碼本身沒有錯誤* ...然後... *只是在單元格中返回此錯誤* ...所以如果代碼沒有將值返回給單元格,那麼必須有代碼關閉。如果您在代碼中放置了一個斷點,然後在它所在的單元格中點擊「F2」,您可以一行一行地逐步查看它爲何返回錯誤消息。但我認爲@ScottCraner你照顧了:) –