excel - 循环遍历所有打开的工作簿时,代码在一个工作簿后退出循环
问题描述
我想遍历所有打开的 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 循环。
解决方案
那是因为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
推荐阅读
- apache-spark - Spark 3.0 - 从 MQTT 流中读取数据
- ms-access - 如何使用另一个 vba 访问代码在 Access 中编写 vba 代码?
- java - MongoDB对同一文档的并发更新不是原子的
- ms-access - MS Access 表单从多个(不相关的)表中获取数据
- javascript - 下一个光滑的滑块在图像中不起作用
- javascript - 如何让程序等待按钮单击以转到方法中的下一个循环迭代?[JavaScript]
- c# - Windows 窗体:删除树视图左侧的空白区域
- javascript - 在另一个 HTML 元素中附加 HTML 元素
- excel - vba 匹配函数区分大小写
- hyperledger-fabric - 使用 Hyperledger Caliper 对不同机器中的 Hyperledger 织物进行基准测试