2012-07-19 98 views
4

我想返回一個範圍的列數,有時我需要一個範圍,但有時我需要多個範圍。在vba函數中的可選範圍

我已經把可選範圍,所以我可以選擇多個範圍。如果我在電子表格中未提供的函數原型中引用一個範圍,我會得到#Value!錯誤。

我需要一種方法來檢查可選範圍是否爲空,無效空等,所以我不必引用範圍。

這是VBA函數原型: -

Function GetColoumnCount(ARange1 As Range, Optional ARange2 As Range, Optional ARange3 As Range, Optional ARange4 As Range) As Integer 

    Dim Result As Integer 
    Result = 0 

    Result = ARange1.Columns.Count ' This works 
    Result = ARange1.Columns.Count + ARange2.Columns.Count ' This doesn't work 

    GetColoumnCount = Result  
End Function 

在我的電子表格我在該函數的工作單元格中輸入此。
=GetColoumnCount(BC34:BK34, BC35:BD35, BE35:BF35, BG35:BH35)
這打破了具有可選參數的目的。

回答

2

嘗試像這樣

Function GetColoumnCount(ARange1 As Range, Optional ARange2 As Range, Optional ARange3 As Range, Optional ARange4 As Range) As Long 
    Dim Result As Long 
    Result = 0 

    Result = ARange1.Columns.Count ' This works 
    If Not ARange2 Is Nothing Then 
     Result = Result + ARange2.Columns.Count 
    End If 

    GetColoumnCount = Result  
End Function 
+0

@GrooverMD這個公式將雙數列的重疊(即BC:BD在你的例子) - 是你的意圖是什麼? – brettdj 2012-07-19 04:43:24

1

如果您使用的參數,你可以提供一個可變數量的參數ParamArray關鍵字。

Public Function GetColumnCount(ParamArray Ranges() As Variant) As Long 

    Dim lReturn As Long 
    Dim i As Long 
    Dim rResult As Range 
    Dim rArea As Range 

    'Loop through the Ranges array supplied by ParamArray 
    For i = LBound(Ranges) To UBound(Ranges) 
     'Only work with those array members that are ranges 
     If TypeName(Ranges(i)) = "Range" Then 
      'Use Union to combine all the ranges 
      If rResult Is Nothing Then 
       Set rResult = Ranges(i) 
      Else 
       Set rResult = Application.Union(rResult, Ranges(i)) 
      End If 
     End If 
    Next i 

    'Loop through the Areas and add up the columns 
    If Not rResult Is Nothing Then 
     For Each rArea In rResult.Areas 
      lReturn = lReturn + rArea.Columns.Count 
     Next rArea 
    End If 

    GetColumnCount = lReturn 

End Function 

要使用:

=getcolumncount(E2:K18) = 7 
=getcolumncount(D4:L14,N4:P14) =12 (9+3) 
=getcolumncount(C7:F15,H7:L15,K7:N15) =11 (omits double counting overlap) 
+0

+1高效處理各種尺寸範圍輸入 – brettdj 2012-07-20 04:02:14