Access/Excel VBA-跳过每个循环

Access/Excel VBA-跳过每个循环,excel,ms-access,vba,Excel,Ms Access,Vba,以下代码编辑多个excel工作簿,但在编辑工作簿之前,它首先检查工作簿是否处于读/写模式。如果不是,它将关闭并打开工作簿,直到读/写激活 我担心的是,如果我不在下一个工作簿中加入某种转义选项,这个循环将永远持续下去 如果循环达到一定次数(例如5次),是否有一种方法可以实现一个带有“重试”和“跳过”按钮的简单对话框 重试–重新尝试循环 跳过-跳到下一个工作簿 For Each i In MyArray xl.Workbooks.Open (i) 'If workbook in r

以下代码编辑多个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

或者,如果您只是在查找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次失败后)则会在重试前提前退出。

循环所有工作簿。在该循环中,循环当前工作簿中的所有工作表。您可以每次递增一个变量,并在循环之前检查是否已达到某个值。