vba检查是否打开了只读工作簿

时间:2013-12-05 22:20:32

标签: vba save readonly

我似乎无法得到关于是否打开只读工作簿的明确反馈。在我的代码中,我在关闭/保存工作簿后将其复制。我希望能够覆盖只读工作簿,如果它被另一个用户打开为只读。我尝试过这样的代码,但没有运气,它只是说“文件没有打开!”即使我把它打开了。 如何检查vba中是否打开了“只读.xlsx”文件?

Sub Test_If_File_Is_Open_2()

Dim wBook As Workbook

On Error Resume Next

Set wBook = Workbooks("C:\Users\" & Environ("username") & "\Documents\Dropbox\Systems\Open     Machine Schedule\Open Machine Schedule.xlsx")
If wBook Is Nothing Then 'Not open
MsgBox "File is Not open!"
Else 'It is open
MsgBox "File is Open!" 'Never get this to display when I have the excel file open

End If

End Sub

启动使用这段代码(上面)的提示是因为如果另一个用户打开了只读工作簿,我希望宏不会导致错误。当我运行下面的宏并且之前打开复制的只读工作簿时,我收到一个错误:“vba运行时错误1004无法访问只读文档” 复制的工作簿关闭时,我不会收到此错误,它会像预期的那样覆盖它。 以下是提示此问题的代码:

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim backupfolder As String

backupfolder = "C:\Users\" & Environ("username") & "\Documents\Dropbox\Systems\Open Machine Schedule\"

ThisWorkbook.SaveAs Filename:=backupfolder & "Open Machine Schedule - Current.xlsx", FileFormat:=xlOpenXMLWorkbook
End Sub

Sub Auto_Save()

Dim savedate

savedate = Date

Dim savetime
savetime = Time
Dim formattime As String
formattime = Format(savetime, "hh.MM.ss")
Dim formatdate As String
formatdate = Format(savedate, "DD - MM - YYYY")


Application.DisplayAlerts = False

Dim backupfolder As String
backupfolder = "C:\Users\" & Environ("username") & "\Documents\Dropbox\Systems\Open Machine Schedule\"
ActiveWorkbook.Save
ActiveWorkbook.SaveAs backupfolder & "Open Machine Schedule - Current.xlsx", FileFormat:=xlOpenXMLWorkbook
SetAttr backupfolder & "Open Machine Schedule - Current.xlsx", vbReadOnly
Application.DisplayAlerts = True
MsgBox "Backup Run. Please Check at: " & backupfolder & " !"

End Sub

非常感谢任何帮助/建议

1 个答案:

答案 0 :(得分:10)

您的第一个代码只是测试工作簿是否存在而不是其状态。

你可以改用它:

If wBook.ReadOnly Then
    MsgBox "File is Read-only"
Else
    MsgBox "File is not read-only"
End If