首页 > 解决方案 > 循环遍历所有打开的工作簿时,代码在一个工作簿后退出循环

问题描述

我想遍历所有打开的 Excel 工作簿,以确定要在哪个工作簿上执行操作。问题是,代码在活动工作簿之后退出 for 循环并返回“Nothing”,无论我打开了多少工作簿。

我需要每周运行此例程,以将工作时间从下载的 Excel 工作簿转移到备用工作簿中。文件名称每周更改,但始终以“时间表”开头

从一月到四月,我每周都使用这个程序,没有任何问题。我今天尝试使用它,但出现了这个问题。我已经在几台具有不同操作系统(Windows 7、Windows 10)的不同计算机上使用了该例程。

我已保存、关闭并重新打开要激活的工作簿,但无济于事。我不想每周都更改代码来访问特定的工作簿,而是使用文件名中的前 4 个字母来标识要对其执行操作的文件。

Sub cmdImportHours_Click()

    Dim ThisWB As Workbook
    Dim ImportWB As Workbook
    Dim WB As Workbook
    Dim msg1 As String
    Dim msg As Variant

' more variables

    msg1 = "Required file not found. Open the import file and try again."

    Set ThisWB = ThisWorkbook
    ThisWB.Worksheets("Hours").Activate

'The following loop exits after one iteration (the active workbook),
'regardless of how many workbooks are open

    For Each WB In Workbooks
        If Left(WB.Name, 4) = "Time" Then
            WB.Activate
            Exit For
        End If
    Next WB

    If WB Is Nothing Then
        msg = MsgBox(msg1, vbOKOnly)
        Exit Sub
    End If

'more code

End Sub

我希望循环查看每个打开的 Excel 工作簿的名称,但它仅在查看活动工作簿后退出 For 循环。

标签: excelvba

解决方案


那是因为Exit For,只需评论该行。并且不要使用WB外部for each使用其他变量,在此代码变量count中用于计算匹配的工作簿

Dim count As String
count = 0
For Each WB In Workbooks
    If Left(WB.Name, 4) = "Time" Then
        count = count + 1
        WB.Activate
        'Exit For
    End If
Next WB

If count < 1 Then
    msg = MsgBox(msg1, vbOKOnly)
    Exit Sub
End If

推荐阅读