![](/img/trans.png)
[英]Excel VBA to create a multidimensional array from non-adjacent table columns
[英]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.