2017-05-04 263 views
1

因此,我想創建一個基本函數,該函數需要我在Excel中突出顯示的平均值。我很清楚Excel中已經有了一個內置的函數,但我正在努力使其成爲練習。通過VBA中的函數傳遞數組或範圍

我的問題是我不知道如何通過一個範圍,然後調用範圍中的特定元素。

下面是我一直在玩的僞代碼。我知道這可能會寫得很糟糕。我是初學者,我只想得到一些練習。

Function averagetest(range As Range) '<------(Is this how I pass a Range into a function?) 
     Dim N as Integer 
     Dim i as Integer 
     Dim average as Double 
     average = 0 
     N = LengthofRange '<--------- (Is there a way to get the length of the 
     range like UBound or LBound for an array?) 
     Do Until i = LengthofRange 
      average = average + Range(i, i+1) '<--------(Is this how you call a 
      specific element in the range? I'm just adding every element in the 
      Range) 
      i = i + 1 
     Loop 
average = average/N 

End Function 

回答

1

您不能假定Range會連續,也不能假設Range將是水平的,也不是垂直的。

A Range是對象的集合,因此您可以使用For Each循環來迭代它以獲得最佳性能。

假設功能是指被用作UDF工作表函數,因此,在一個標準模塊(.BAS)定義:

Public Function AverageTest(ByVal target As Range) As Variant 

    Dim total As Double 
    Dim count As Double 

    Dim cell As Range 
    For Each cell In target 
     If IsNumeric(cell.Value) Then 
      total = total + cell.Value 
      count = count + 1 
     'Else 
     ' AverageTest = CVErr(xlErrValue) 
     ' Exit Function 
     End If 
    Next 

    If count = 0 Then 
     AverageTest = CVErr(xlErrDiv0) 
    Else 
     AverageTest = total/count 
    End If 

End Function 

注:

  • 參數是通過ByVal,並且不以現有類型命名(Range);我們不需要對範圍指針的引用,它的副本就足夠了。
  • 功能明確Public,並有明確的返回類型(Variant)。
  • 函數返回Variant,以便在適用的情況下返回Double結果「歡樂路徑」或適當的Error值(#Div/0!)。
  • 函數僅對數值單元格進行計數,這意味着即使target範圍包含錯誤值,它也能正常工作。如果遇到非數字值,註釋掉的代碼將退出並返回一個#VALUE!錯誤。

你如何「打發範圍」是調用者的問題。有很多方法可以做到這一點 - 從Excel公式:

=AverageTest(A1:A10) 
=AverageTest(A1:B12,F4:L4) 

你也可以用它在VBA代碼:

foo = Module1.AverageTest(ActiveSheet.Range("A1:D10")) 
1

請勿使用range作爲變量。

然後你可以使用rows.Count或Columns.Count拿到程度

Function averagetest(rng As Range) 
     Dim N as Integer 
     Dim i as Integer 
     Dim average as Double 
     average = 0 
     N = rng.rows.count 
     For i = 1 to N 'use For loop 
      average = average + rng.cells(i,1)'Cells will work here 
     Next i 
     averagetest= average/N 

End Function 

或者你也可以做到這一點 - 有沒有真正的任何需要遍歷細胞的數量,當你可以在rng.Cells集合中迭代Each單元格。我還改變從average變量名(其被誤導)爲更具說明性的一點,像total

Option Explicit 
Function averagetest(rng As Range) 
    Dim cl As Range 
    Dim total As Double 

    For Each cl In rng.Cells 
     total = total + cl.Value 
    Next 
    averagetest = total/rng.Cells.Count 

End Function 

作爲獎勵,這後一種方法將在2維範圍正常工作。

請注意,這會將空單元格視爲0值(AVERAGE工作表函數忽略空單元格,因此您的結果可能會有所不同),並且如果範圍中存在非數字值,則會引發錯誤。