我有一个包含 50 个 .xlsx 文件的目录。我需要将这些发送给某人,但由于他们的工作环境限制,我无法使用 Winzip。
我之前已手动对每个 .xlsx 文件进行密码保护,但想知道是否有一种自动方式可以做到这一点?这是因为我定期更新这些文件(为了方便起见,删除了密码),然后在发送之前重新应用密码。
最佳答案
以下 VBA 例程将打开所有文件(您将看不到它),并使用密码或不使用密码保存它们。
Option Explicit
Const FOLDER As String = "C:\Temp\Test xl file bulk pw protection\"
Const PASSWORD As String = "weakpassword"
Dim app As Excel.Application
Dim strFile As String
Dim wb As Workbook
Sub Password_ON()
Set app = New Excel.Application
strFile = Dir(FOLDER)
app.DisplayAlerts = False
Do While Len(strFile) > 0
Set wb = app.Workbooks.Open(FOLDER & strFile)
wb.SaveAs wb.FullName, , PASSWORD
wb.Close
strFile = Dir
Loop
app.DisplayAlerts = True
app.Quit
Set app = Nothing
End Sub
Sub Password_OFF()
Set app = New Excel.Application
strFile = Dir(FOLDER)
app.DisplayAlerts = False
Do While Len(strFile) > 0
Set wb = app.Workbooks.Open(FOLDER & strFile, , , , PASSWORD)
wb.SaveAs wb.FullName, , vbNullString
wb.Close
strFile = Dir
Loop
app.DisplayAlerts = True
app.Quit
Set app = Nothing
End Sub
由于打开和关闭文件需要时间,因此这不是一个非常快的过程。以下例程实际上并不更快,但它们心理上更快,正如您可以在状态栏中看到正在处理哪个文件。
Sub Password_ON()
Set app = New Excel.Application
strFile = Dir(FOLDER)
app.DisplayAlerts = False
Do While Len(strFile) > 0
Application.StatusBar = "Processing " & strFile
DoEvents
Set wb = app.Workbooks.Open(FOLDER & strFile)
wb.SaveAs wb.FullName, , PASSWORD
wb.Close
strFile = Dir
Loop
app.DisplayAlerts = True
app.Quit
Set app = Nothing
Application.StatusBar = "READY"
End Sub
Sub Password_OFF()
Set app = New Excel.Application
strFile = Dir(FOLDER)
app.DisplayAlerts = False
Do While Len(strFile) > 0
Application.StatusBar = "Processing " & strFile
DoEvents
Set wb = app.Workbooks.Open(FOLDER & strFile, , , , PASSWORD)
wb.SaveAs wb.FullName, , vbNullString
wb.Close
strFile = Dir
Loop
app.DisplayAlerts = True
app.Quit
Set app = Nothing
Application.StatusBar = "READY"
End Sub
关于excel - 密码保护目录中的多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33347972/