2016-10-21 90 views
0

我有一個用戶定義的函數,如下所示,允許我將兩個不相鄰的列組合成一個連續的數組。Excel VBA非連續陣列用戶定義函數修復

Function MakeContig(ParamArray av() As Variant) As Variant 
    Dim avOut() As Variant 
    Dim i  As Long 
    Dim j  As Long 

    ReDim avOut(1 To av(0).Count, 0 To UBound(av)) 
    For j = 0 To UBound(av) 
     For i = 1 To av(j).Rows.Count 
      avOut(i, j) = av(j)(i) 
     Next i 
    Next j 
    MakeContig = avOut 
End Function 

所以,如果I型 「= makecontig(A1:A5,E1:E5)」 引入細胞中,形成一個單一的陣列,其中包括兩列的包括在公式中。我希望能夠編輯該函數,以便它忽略包含錯誤或任何類型的非數組條目的數組條目。例如,如果我鍵入「= makecontig(A1:A5,E1:E5,)」或「= makecontig(A1:A5,Nothing,E1:E5)」或「= makecontig(A1:A5, E1:E5,C1:C5 *#N/A)「我希望它忽略錯誤或空白參數,並且只爲A1:A5和E1:E5創建一個連續數組。

我想我需要在UDF的某個地方包含一個If/Then語句,但我似乎無法弄清楚如何正確執行它。

任何幫助,將不勝感激!

回答

0

您需要測試,如果該參數是一個範圍或不:

Function MakeContig(ParamArray av() As Variant) As Variant 
    Dim avOut() As Variant 
    Dim i  As Long 
    Dim j  As Long 
    Dim x As Long 
    Dim t As Long 
    x = -1 
    For j = 0 To UBound(av) 
     If TypeName(av(j)) = "Range" Then 
      x = x + 1 
      If av(j).Count > t Then 
       t = av(j).Count 
      End If 
     End If 
    Next j 
    ReDim avOut(1 To t, 0 To x) 
    t = 0 
    For j = 0 To UBound(av) 
     If TypeName(av(j)) = "Range" Then 
     For i = 1 To av(j).Rows.Count 
      avOut(i, t) = av(j)(i) 
     Next i 
     t = t + 1 
     End If 
    Next j 
    MakeContig = avOut 
End Function 

正如你可以看到:只有

MakeContig($F$1:$F$8+#N/A,$A$1:$A$26,$C$1:$C$26,$B$1:$B$4*#N/A) 

回報2列寬陣列:

enter image description here

+0

太棒了!真的很感謝這一點 – Shawn