需要更正VBA代码。获取错误消息。"对于已在使用的控制变量"

时间:2016-04-12 10:46:45

标签: excel vba

我在Excel中使用VBA。

我收到一条错误消息,指出控制变量已在使用中。当弹出错误时,第二个 For Each r In 会在VBA编辑器中突出显示。任何人都可以帮助更正此代码。谢谢

Dim ws As Worksheet
Dim r As Range

For Each ws In Worksheets
    If InStr(1, ws.Name, "Wk", 1) > 0 Then
        For Each r In ws.Range("C118:I124")
        For Each r In ws.Range("C163:J168")
        For Each r In ws.Cell(E2, E15, E28, E41, E54, E67, E80)
            r.Formula = Replace(r.Formula, "Wk1", r.Parent.Name)
        Next r
    End If
Next ws

MsgBox "Done"
End Sub

1 个答案:

答案 0 :(得分:0)

您尝试运行三个不同的范围,即连接这些范围。然而,这不是For-Each的工作原理,你必须将其分解。

Dim ws As Worksheet
Dim r As Range

For Each ws In Worksheets
    If InStr(1, ws.Name, "Wk", 1) > 0 Then
        For Each r In ws.Range("C118:I124")
            r.Formula = Replace(r.Formula, "Wk1", r.Parent.Name)
        Next r

        For Each r In ws.Range("C163:J168")
            r.Formula = Replace(r.Formula, "Wk1", r.Parent.Name)
        Next r

        Range("E2").Formula = Replace(Range("E2").Formula, "Wk1", Range("E2").Parent.Name)
        Range("E15").Formula = Replace(Range("E15").Formula, "Wk1", Range("E15").Parent.Name)
        Range("E28").Formula = Replace(Range("E28").Formula, "Wk1", Range("E28").Parent.Name)
        Range("E41").Formula = Replace(Range("E41").Formula, "Wk1", Range("E41").Parent.Name)
        Range("E54").Formula = Replace(Range("E54").Formula, "Wk1", Range("E54").Parent.Name)
        Range("E67").Formula = Replace(Range("E67").Formula, "Wk1", Range("E67").Parent.Name)
        Range("E80").Formula = Replace(Range("E80").Formula, "Wk1", Range("E80").Parent.Name)
    End If
Next ws

MsgBox "Done"
End Sub

编辑:已更改以适应评论。它不是更漂亮,但我担心没有办法让几个松散的细胞更优雅。