excel - 工作簿是只读的,再试一次

标签 excel vba readonly

我有这段代码可以检查以确保工作簿未打开/未在使用中。
我将如何修改它以在 5 秒内重试并在 3 次尝试后发送 MsgBox?

 If wBook.ReadOnly = True Then
        MsgBox "Database is in use. Please try after sometimes.", vbookonly + vbCritical, "error"
        
        Exit Sub
    End If

最佳答案

您可以使用辅助方法,根据您传递的参数,您可以灵活地等待多少时间:

Public Sub TryWriteMode(ByVal book As Workbook _
                      , ByVal numberOfTries As Long _
                      , ByVal secondsWaitAfterFailedTry As Long)
    Const maxSecondsWait As Long = 60
    If book Is Nothing Then
        Err.Raise 91, "TryWriteMode", "Book not set"
    End If
    If numberOfTries < 1 Then Exit Sub
    '
    'Cap seconds
    If secondsWaitAfterFailedTry < 0 Then
        secondsWaitAfterFailedTry = 0
    ElseIf secondsWaitAfterFailedTry > maxSecondsWait Then
        secondsWaitAfterFailedTry = maxSecondsWait
    End If
    '
    Dim i As Long
    Const secondsPerDay As Long = 24& * 60& * 60&
    '
    For i = 1 To numberOfTries
        On Error Resume Next
        book.ChangeFileAccess xlReadWrite
        On Error GoTo 0
        If Not book.ReadOnly Then Exit Sub
        Application.Wait Now() + secondsWaitAfterFailedTry / secondsPerDay
    Next i
End Sub
在您的示例中,您可以这样调用:
If wBook.ReadOnly = True Then
    TryWriteMode book:=wBook _
               , numberOfTries:=3 _
               , secondsWaitAfterFailedTry:=5
End If
If wBook.ReadOnly Then
    MsgBox "Database is in use. Please try again later.", vbOKOnly + vbInformation, "Read-only book"
    Exit Sub
End If

关于excel - 工作簿是只读的,再试一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72805995/

相关文章:

objective-c - 只读 socket ?

c# - 是否可以返回调用者无法修改的只读 ObservableCollection?

excel - 如何将文本拆分为列,直到遇到大写字母或数字

c# - 如何使用 EPPlus 隐藏 Excel 电子表格中的大量列?

image - 将图片作为 http GET 响应获取并插入电子表格而不保存图片

excel - 将数组变量传递给 Excel 命名范围以进行数据验证列表

Excel If 公式 - 通用错误消息

excel - 在 Excel 中剪切/粘贴同一行中的重复金额

excel - 模拟使用 CTRL+A 快捷键选择 block 的 VBA 代码是什么?

c# - 我在 Visual Studio 中的项目是只读的。我做了什么?