将两个不相邻的列分组到Excel VBA脚本的二维数组中

我想这个问题可能与Excel女士 – > 2列成2维数组,但我不能完全连接。

我有一个VBA脚本来填补遗漏的数据。 我select两个相邻的列,它find第二列中的任何间隙,并基于第一列中的(可能不规则的)间距进行线性内插。 例如,我可以在这个数据上使用它:

1 7 2 14 3 21 5 35 5.1 6 42 7 8 9 45 

得到这个输出

 1 7 2 14 3 21 5 35 5.1 35.7 <---1/10th the way between 35&42 6 42 7 43 <-- 1/3 the way between 42 & 45 8 44 <-- 2/3 the way between 42 & 45 9 45 

这对我来说非常有用。

我的麻烦是它只能在连续的列上工作。 我希望能够select两个不相邻的列,并以相同的方式工作。 我的代码是这样开始的:

 Dim addr As String addr = Selection.Address Dim nR As Long Dim nC As Long 'Reads Selected Cells' Row and Column Information nR = Range(addr).Rows.Count nC = Range(addr).Columns.Count 

当我运行这个选定的连续列时, addr在“Locals”窗口中显示一个类似"$A$2:$B$8"nC = 2

当我select连续的列时, addr在Locals窗口中显示一个类似"$A$2:$A$8,$C$2:$C$8"nC = 1的值。

稍后在脚本中,我将每列中的值收集到一个数组中。 以下是我如何处理第二列,例如:

  'Creates a Column 2 (col1) array, determines cells needed to interpolate for, changes font to bold and red, and reads its values Dim col2() As Double ReDim col2(0 To nR + 1) i = 1 Do Until i > nR If IsEmpty(Selection(i, 2)) Or Selection(i, 2) = 0 Or Selection(i, 2) = -901 Then Selection(i, 2).Font.Bold = True Selection(i, 2).Font.Color = RGB(255, 69, 0) col2(i) = 9999999 Else col2(i) = Selection(i, 2) End If i = i + 1 Loop 

因为即使我的select是"$A$2:$A$8,$C$2:$C$8" VBA也会将Selection(1,2)视为对$B$2的引用,而不是所需的$C$2

任何人都有一个build议,我可以如何让VBA将不连续的select视为连续的对待?

你正在处理“不相交的范围”。 使用Areas集合,例如,如下所述。 第一列应该在Selection.Areas(1) ,第二列应该在Selection.Areas(2)