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

如何通过cmd或VBA删除文件的写保护?,vba,cmd,Vba,Cmd,我正在为word和excel编写宏。输出是应保存的生成文件。 由于这些文件已经存在并且是写保护的,我不得不以某种方式删除保护。我在excel中发现了一个不受保护的函数,但它实际上不起作用。 我也没有找到任何通过cmd o0取消保护的命令 在保存新文件之前,我考虑过删除这些文件。 但我想找到一个解除保护的解决方案。尝试使用cmd中的attrib命令来更改文件属性 attrib*.xls-r将帮助您删除只读属性。尝试cmd中的attrib命令以更改文件属性 attrib*.xls-r将帮助您删除只读

我正在为word和excel编写宏。输出是应保存的生成文件。 由于这些文件已经存在并且是写保护的,我不得不以某种方式删除保护。我在excel中发现了一个不受保护的函数,但它实际上不起作用。 我也没有找到任何通过cmd o0取消保护的命令

在保存新文件之前,我考虑过删除这些文件。
但我想找到一个解除保护的解决方案。

尝试使用cmd中的attrib命令来更改文件属性
attrib*.xls-r将帮助您删除只读属性。

尝试cmd中的attrib命令以更改文件属性
attrib*.xls-r将帮助您删除只读属性。

以下是使用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
用法:

RemoveReadOnly "C:\mydir\myReadOnlyFile.dat"
更多信息:

注意:以上要求按如下方式设置参考:工具>参考…>在Microsoft脚本运行时旁边设置复选标记

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

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

以下是使用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
用法:

RemoveReadOnly "C:\mydir\myReadOnlyFile.dat"
更多信息:

注意:以上要求按如下方式设置参考:工具>参考…>在Microsoft脚本运行时旁边设置复选标记

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

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

+1尽管演示如何从VBA调用它会很有帮助,但+1尽管演示如何从VBA调用它也会很有帮助