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

 炽热冰菊66 发布于 2023-02-12 15:55

我似乎无法得到关于是否打开只读工作簿的明确反馈.在我的代码中,我在关闭/保存工作簿后将其复制.我希望能够覆盖只读工作簿,如果它被另一个用户打开为只读.我尝试过这样的代码,但没有运气,它只是说"文件没有打开!" 即使我把它打开了.如何检查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 个回答
  • 您的第一个代码只是测试工作簿是否存在而不是其状态.

    您可以使用此代替:

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

    2023-02-12 15:58 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有