For Loop未运行。条件工作正常,但在引用另一个工作簿时循环未运行

时间:2014-06-23 08:33:50

标签: vba excel-vba excel

我想根据 Book1的值更改一些 Book2 值。

Book1 中的宏代码:

Dim i As Integer
Dim k As Integer
k = Range("Z1")
For i = 1 To k
    If Cells(i, 22).Value = "Yes" Then
        Windows("Book2").Activate
        Cells(i, 11) = ""
        Cells(i, 13) = ""
    End If
Next i

1 个答案:

答案 0 :(得分:1)

如评论所述,您可以尝试重写这样的代码:

Dim i As Long
Dim ws1 As Worksheet, ws2 As Worksheet

Set ws1 = Workbooks("Book1").Sheets("Sheet1") '~~> change sheet name to suit
Set ws2 = Workbooks("Book2").Sheets("Sheet1")

With ws1
    For i = 1 to .Range("Z1").Value
        If .Cells(i, 22).Value = "Yes" Then
            ws2.Cells(i, 11).Value = ""
            ws2.Cells(i, 13).Value = ""
        End If
    Next
End With