我已经查看了vba Union方法,但该示例仅显示了如何将公式应用于这些范围。每当我尝试将这些范围复制到一个数组中时,我最终只会使用一些列。我这样做:
Dim aRng As Range: Set aRng = wbkFirstfile.Sheets(1).Range("H2:H" + CStr(lastRow))
Dim bRng As Range: Set bRng = wbkFirstfile.Sheets(1).Range("P2:P" + CStr(lastRow))
Dim cRng As Range: Set cRng = wbkFirstfile.Sheets(1).Range("Q2:Q" + CStr(lastRow))
Dim dRng As Range: Set dRng = wbkFirstfile.Sheets(1).Range("U2:U" + CStr(lastRow))
Dim eRng As Range: Set eRng = wbkFirstfile.Sheets(1).Range("V2:V" + CStr(lastRow))
Dim fRng As Range: Set fRng = wbkFirstfile.Sheets(1).Range("W2:W" + CStr(lastRow))
Dim uRng As Range: Set uRng = Union(aRng, bRng, cRng)
Dim uRng2 As Range: Set uRng2 = Union(dRng, fRng)
这仅适用于6列中的3列,即使我尝试直接访问它,例如area(3).cells(r,c)等...我得到了一个应用程序定义的错误。
更新
我还将uRng更新为:
Dim uRng As Range: Set uRng = Union(aRng, bRng, cRng, dRng, eRng, fRng)
我尝试以下列方式访问它:
MsgBox uRng2.Areas(1).Cells(2, 1)
或
MsgBox uRng2.Areas(2).Cells(2, 1)
或
MsgBox uRng2.Areas(3).Cells(2, 1)
并且它工作正常....区域3之后的任何事情(我认为有6个区域)会导致应用程序定义错误。
有什么想法吗?
答案 0 :(得分:3)
由于您只需要一个值数组,因此可以将Index
与几个数组参数一起使用:
Dim v
With wbkFirstfile.Sheets(1).Range("H2:W" & lastRow)
v = Application.Index(.Value2, .Worksheet.Evaluate("ROW(" & .Columns(1).Address & ")-1"), Array(1, 9, 10, 15, 16))
End With
Evaluate
部分创建一个'row'索引数组(从1到n),最后一个数组是所需列的索引(相对于范围,因此H是第1列)。 / p>