Excel VBA:迭代多个范围

时间:2016-03-31 12:00:42

标签: excel vba excel-vba

我目前正在编写一个自动执行goalseek的代码,但我遇到了语法问题。

我宣布了3个变量:

Dim X as Range
Dim Y as Range
Dim Z as Range

Set X as Range(....)
Set Y as Range(....)
Set Z as Range(....)

For each cell in X,Y,Z
X.GoalSeek Goal:=Y, ChangingCell:=Z
Next cell in X,Y,Z

这是伪代码,但我希望它在X,Y,Z范围内的每个单元格中逐个迭代。

这些是列范围。

问题:如何让X,Y,Z范围内的每个单元格迭代进入goalseek函数?因此,如果每个范围有5个单元格,它将运行5次。

1 个答案:

答案 0 :(得分:1)

  1. For ... Each不允许在in之后使用逗号分隔的参数,因此您必须向其提供“一个”范围...

  2. 如果您想说For Each cell ...,那么您必须使用.Cells属性将范围分解为单元格

  3. For ... Each内你应该使用循环变量(cell)而不是XYZ

  4. 实施例

    Sub Test()
    Dim X As Range, Y As Range, Z As Range
    Dim C As Range
    
        Set X = [A1]
        Set Y = [B1:B2]
        Set Z = [C1:C3]
    
        For Each C In Union(X.Cells, Y.Cells, Z.Cells)
            MsgBox C.AddressLocal
        Next C
    End Sub
    

    Union(...)的替代语法是

    For Each C In Union(X, Y, Z).Cells
    

    这可能会让你更清楚的是你将3个范围捆绑在一起然后解决他们的每个细胞......可能是品味问题

    修改  假设你想要形成你的(相等大小)范围的TRIPLES并将它们输入单个函数,计算Y和Z范围的偏移到X

    例如

    Sub Test()
    Dim X As Range, Y As Range, Z As Range
    Dim C As Range
    Dim OYR As Long, OYC As Long, OZR As Long, OZC As Long
    
        Set X = [A1:A5]
        Set Y = [B3]        'no need to provide full range, starting point will do
        Set Z = [C5]
    
        ' calculating offsets
        OYR = Y(1, 1).Row - X(1, 1).Row + 1
        OYC = Y(1, 1).Column - X(1, 1).Column + 1
    
        OZR = Z(1, 1).Row - X(1, 1).Row + 1
        OZC = Z(1, 1).Column - X(1, 1).Column + 1
    
        ' iterate thru all cells of X and their equally ofsett partners in Y and Z
        For Each C In X.Cells
            MsgBox C.AddressLocal & " " & C(OYR, OYC).AddressLocal & " " & C(OZR, OZC).AddressLocal
        Next C
    
    End Sub