Access / Excel VBA - 跳过每个循环

时间:2015-08-25 18:27:39

标签: vba excel-vba ms-access access-vba excel

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

我担心如果我没有将某种转义选项合并到下一个工作簿中,这个循环将永远持续。

如果循环达到一定数量的尝试,有没有办法实现带有“重试”和“跳过”按钮的简单对话框,例如5

重试 - 重新尝试循环

跳过 - 跳到下一个工作簿

{{1}}

2 个答案:

答案 0 :(得分:1)

我会添加一个计数器变量来跟踪循环运行的次数,然后一旦超过阈值就弹出表单。

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

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

答案 1 :(得分:0)

或者,如果你只是在寻找msgbox部分,你可以使用这样的东西来询问用户是否要继续并告知他们尝试号码:

Sub doloop()
    Dim i As Integer
    Dim answer
    Do
        i = i + 1
        answer = MsgBox("Try again?", vbQuestion + vbYesNo, "Attempt " & i & " Failed!")
        If answer = vbNo Then Exit Sub
    Loop
End Sub

或者你可以在你自己的循环结束之前问这个:

 If 'Condition to check that it failed' Then
        i = i + 1
        If i > 4 then
            answer = MsgBox("Try again?", vbQuestion + vbYesNo, "Attempt " & i & " Failed!")
            If answer = vbNo Then Exit Sub
        End if

       'Code to retry'
 End if

这会使msgBox重新启动,并在重试之前提前退出(如果用户按下No)(仅在4次失败后)