可变范围作为input

我是Excel的VBA的新用户(2013年),我一直在努力解决问题。

我想创build一个函数,在用户必须提供的其他inputvariables中,有几个单元格范围,应该是可变的,并且由用户自己“容易地select”。 它应该是类似于(例如)Excel“SUM”公式,您可以在其中input几个范围,如“A1:C1,F1:H1,…”,用鼠标select它们。

此外,我必须传输用户在二维数组中select的值。 用户select的每个范围必须成为我的二维数组的一行。

除了我迄今为止所说的,用户input的范围数量应该是任何人,只有第一个范围是强制性的。

鉴于电子表格的“结构”,用户必须select的所有数据都按行排列。 (如果它们按行或列排列,会有什么不同?)

请注意,我不应该使用“input框”,因为当我“向下拖动”一行将公式应用到活动窗口下面的许多行时,会减慢很多程序。

下面,我报告我能写的代码的唯一部分(不是很多…)

Function Trial_Version(MyRange1 As Range, MyRange2 As Range, MyRange3 As Range) As Double ''' The number of ranges that the user is be able to input '''should be anyone. Only the first Range should be mandatory Dim TotalArray()() As Double '''The user should be able to input as many "sub-arrays" as they want, '''so I do not know how many parentheses to write TotalArray = (MyRange1)(MyRange2) '''here, the same problem as the previous line RANGE_TO_ARRAY = TotalArray '''This is the output of my function End Function 

提前非常感谢你,奥兰多

不是完整的答案,但希望指出你在正确的方向。

  • 一个标准的Range对象可以容纳多个“区域”(例如C5:D9,G9:H16,B14:D18)。 您可以使用.Areas属性来遍历这些内容。

  • 通过使用Variantvariables(例如Dim a as Variant,a = SomeRange),您可以轻松地从Range对象中获取二维数组值。 如果select了多个区域,这个方法只会得到第一个区域,所以你需要遍历每个区域来获取所有的值。

  • 下面的代码需要添加validation,加上可能的处理任何列/行偏移(即请参阅与索引有关的循环中的注释)。

公共函数ProcessRange(ByRef rng As Range) 

'# PURPOSE: Process multi-area range Dim rngArea As Range ' Single area in multi-area selection Dim lngCol As Long ' Column in selected range(area), 1 based Dim lngRow As Long ' Row in selected range(area), 1 based Dim avarValues As Variant ' 2D variant array for range(area) values, 1 based ' --> Add validation here <-- ' Go through each area in selected range ' -------------------------------------- For Each rngArea In rng.Areas ' Store the values into 2d array (Row, Column), 1 based avarValues = rngArea ' Show each value held in the array For lngRow = 1 To UBound(avarValues, 1) For lngCol = 1 To UBound(avarValues, 2) ' Note row / column index is NOT necessarily the same as the row/column on the worksheet ' Index 1 will be the first cell in the selected area Debug.Print "Area " + rngArea.Address + ", value in AREA row " & lngRow & ", column " & lngCol & ": " & avarValues(lngRow, lngCol) Next lngCol Next lngRow Next rng End Function