Excel VBA:创建一个UDF以将一维数组拆分为二维数组。我这样做了吗?

时间:2017-05-18 01:42:20

标签: arrays excel vba excel-vba

UDF的目的是接收一维数组并将其拆分为二维数组。新数组的大小应该是动态的。请让我附上代码;

Function SPLITARR(ByRef v() As Variant, MaxRow As Integer) As Variant
  Dim ArraySize As Integer
  Dim MaxCols As Integer
  Dim NewArray() As Variant
  Dim x As Integer, y As Integer, z As Integer

  ArraySize = (UBound(v(), 1) - LBound(v(), 1)) + 1
  MaxCols = ArraySize \ MaxRow

  If ArraySize Mod MaxRow > 0 Then MaxCols = MaxCols + 1
  ReDim NewArray(LBound(v(), 1) To MaxRow, 1 To MaxCols)
  For x = LBound(v(), 1) To UBound(v(), 1)
    y = x Mod MaxRow
    If y = 0 Then y = MaxRow
    z = x \ MaxRow
    If x Mod MaxRow = 0 Then z = z - 1
    NewArray(y, z + 1) = v(x, 1)
  Next
  SPLITARR = NewArray()
End Function

应该被称为;

Sub caller()
Dim a() As Variant
a() = Range("A4:A23")
a() = SPLITARR(a(), 5)
ActiveCell.Resize(UBound(a(), 1), UBound(a(), 2)).Value = a()
End Sub

让范围“A4:A23”的值为(1,2,3,... 20) 并且此调用将返回

1,6,11,16
2,7,12,17
3,8,13,18
4,9,14,19
5,10,15,20

注意:我一直在研究/使用excel VBA仅6个月。

0 个答案:

没有答案