excel - Access/Excel VBA - 跳过每个循环

标签 excel ms-access vba

以下代码编辑多个 Excel 工作簿,但在编辑工作簿之前,它首先检查工作簿是否处于读/写模式。如果不是,那么它将关闭并打开工作簿,直到读/写处于事件状态。

我担心的是,如果我不在下一个工作簿中加入某种转义选项,这个循环将永远持续下去。

如果循环达到一定次数的尝试,例如 5,是否有一种方法可以实现带有“重试”和“跳过”按钮的简单对话框

重试——重试循环

跳过 - 跳到下一个工作簿

For Each i In MyArray

    xl.Workbooks.Open (i)
    'If workbook in read only mode , close and open till read/write is active
    Do Until xl.ActiveWorkbook.ReadOnly = False
        xl.ActiveWorkbook.Close (False)
        If GetAttr(i) = vbReadOnly Then _
            SetAttr i, vbNormal
        xl.Workbooks.Open (i)
    If xl.ActiveWorkbook.ReadOnly = False Then Exit Do
    Loop    'Loop above till read/write active

    '''''More code here when workbook read/write mode
Next

最佳答案

我会添加一个计数器变量来跟踪循环运行了多少次,然后在它超过阈值时弹出表单。

我会将它实现到您的代码中,如下所示:

For Each i In MyArray

xl.Workbooks.Open (i)

'Set an attempts counter
attempts = 0

'If workbook in read only mode , close and open till read/write is active
Do Until xl.ActiveWorkbook.ReadOnly = False
xl.ActiveWorkbook.Close (False)
If GetAttr(i) = vbReadOnly Then _
SetAttr i, vbNormal
xl.Workbooks.Open (i)
If xl.ActiveWorkbook.ReadOnly = False Then Exit Do

'Increment the attempts counter on each pass
attempts = attempts + 1
if attempts > 4 then
    'Create your dialogue box, maybe have it set the attempts 
    '    counter back to zero and try the loop five more times
    '    before hitting this stop again, or have it exit the loop
    '    if the user chooses to skip
end if
Loop    'Loop above till read/write active


‘’’’’More code here when workbook read/write mode


Next

关于excel - Access/Excel VBA - 跳过每个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32211430/

相关文章:

excel - 如何引用旧版本的VBA库?

使用 write.csv 导出数据帧时,用空格 (""或点 ("."替换缺失值(NA)

c# - 与 MS Access 建立连接

带 Excel VBA 的 MySQL ODBC 连接器 - 无法删除记录

vba - Excel 中的 HMAC SHA256 宏

string - 从 Excel VBA 中的字符串中删除 HTML 标签

excel - Excel 中交替行颜色/数字 - VBA

json - 将 JSON 文件导入 MS Access 表

excel - 如何在 Excel VBA 中比较单元格位置?

vba - 出错时继续下一步不起作用