繁体   English   中英

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

[英]Group two non-adjacent columns into 2d array for Excel VBA Script

我认为这个问题可能与Excel女士有关- > 2列到二维数组但我无法完全建立连接。

我有一个VBA脚本来填充丢失的丢失数据。 我选择了两个相邻的列,它在第二列中找到任何间隙,并根据第一列中的(可能是不规则的)间距进行线性插值。 例如,我可以在这些数据上使用它:

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

这对我来说非常有用。

我的麻烦是它只适用于连续的列。 我希望能够选择两个彼此不相邻的列,并使它以相同的方式工作。 我的代码开头是这样的:

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的值

当我在选择了连续列的情况下运行它时, 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

这也被破坏了,因为即使我的选择是"$A$2:$A$8,$C$2:$C$8" VBA会将Selection(1,2)视为$B$2的参考,而不是所需的$C$2

任何人都有一个建议,我怎么能让VBA以对待连续的方式处理非连续选择?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM