如何通过 cmd 或 VBA 删除文件的写保护?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12153976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to remove write protection of a file via cmd or VBA?
提问by lorenz albert
i'm coding a macro for word and excel. The output are generated files that should be saved. Since those files already exist and are write protected, I somehow have to remove the protection. I found a unprotect function in excel but it doesn't really work. I also didn't find any command for unprotecting via cmd o0
我正在为 word 和 excel 编写一个宏。输出是应保存的生成文件。由于这些文件已经存在并且被写保护,我不得不以某种方式取消保护。我在 excel 中发现了一个 unprotect 功能,但它并没有真正起作用。我也没有找到任何通过 cmd o0 取消保护的命令
I thought about deleting the files before saving the new ones. But I'd like to find a solution for unprotecting.
我想在保存新文件之前删除文件。但我想找到一种解除保护的解决方案。
回答by Jitendra Pancholi
try attrib command in cmd to change file attributes
attrib *.xls -r
will help you to remove readonly attribute.
在 cmd 中尝试 attrib 命令更改文件属性
attrib *.xls -r
将帮助您删除只读属性。
回答by Jean-Fran?ois Corbett
Here's a way to remove the read-only attribute from VBA using the FileSystemObject:
下面是一种使用 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
Usage:
用法:
RemoveReadOnly "C:\mydir\myReadOnlyFile.dat"
More info: http://msdn.microsoft.com/en-us/library/5tx15443%28v=vs.85%29.aspx
更多信息:http: //msdn.microsoft.com/en-us/library/5tx15443%28v=vs.85%29.aspx
Note: The above requires setting a reference as follows: Tools > References... > set checkmark next to Microsoft Scripting Runtime.
注意:以上需要设置一个引用如下:工具>引用...>在Microsoft Scripting Runtime旁边设置复选标记。
If you don't want to set a reference, then use late binding instead:
如果您不想设置引用,请改用后期绑定:
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