如何通过cmd或VBA删除文件的写保护?

lor*_*ert 1 vba cmd

我正在为一个单词和excel编写一个宏.输出是应该保存的生成文件.由于这些文件已经存在并且受到写保护,因此我不得不删除保护.我在excel中找到了一个unprotect函数,但它并没有真正起作用.我也没有找到任何通过cmd o0取消保护的命令

我想在保存新文件之前删除文件.但我想找到解除保护的解决方案.

Jit*_*oli 5

在cmd中尝试attrib命令来更改文件属性 attrib *.xls -r将帮助您删除readonly属性.

  • +虽然显示如何从VBA调用它也会有所帮助 (2认同)

Jea*_*ett 5

这是一种使用FileSystemObject从VBA中删除只读属性的方法:

Sub RemoveReadOnly(filePath As String)
    Dim FSO As FileSystemObject
    Dim f As Scripting.File
    Set FSO = New FileSystemObject
    Set f = FSO.GetFile(filePath)

    If fil.Attributes And ReadOnly Then 'It's read-only. Remove that attribute.
        fil.Attributes = fil.Attributes - ReadOnly
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

用法:

RemoveReadOnly "C:\mydir\myReadOnlyFile.dat"
Run Code Online (Sandbox Code Playgroud)

更多信息:http://msdn.microsoft.com/en-us/library/5tx15443%28v=vs.85%29.aspx

注意:以上内容需要按如下方式设置引用:工具>引用...>在Microsoft Scripting Runtime旁边设置复选标记.

如果您不想设置引用,请使用后期绑定:

Sub RemoveReadOnly(filePath As String)
    Dim FSO As Object
    Dim fil As Object    
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set fil = FSO.GetFile(filePath)

    If fil.Attributes And 1 Then '1 = ReadOnly
        fil.Attributes = fil.Attributes - 1
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)