You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA宏如何从TXT文件读取密码打开受密码保护的Excel文件

解决方案

你只需要在原有代码基础上增加读取TXT密码的逻辑即可,具体修改如下:
首先确认你的密码TXT文件路径(示例中假设文件为C:\Users\xxxxx\password.txt,文件内仅存储密码文本,无其他多余字符),替换代码中对应路径即可。

Sub OpenHardLockedUsers()

    Dim MyPath As String
    Dim MyFile As String
    Dim LatestFile As String
    Dim LatestDate As Date
    Dim LMD As Date
    ' 新增变量:存储密码、密码文件路径、文件号
    Dim PwdPath As String
    Dim ReadPwd As String
    Dim FileNum As Integer

    MyPath = "C:\Users\xxxxx"
    ' 此处替换为你的密码TXT文件实际路径
    PwdPath = "C:\Users\xxxxx\password.txt"

    If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

    MyFile = Dir(MyPath & "*.xls", vbNormal)

    If Len(MyFile) = 0 Then
        MsgBox "No files were found...", vbExclamation
        Exit Sub
    End If

    Do While Len(MyFile) > 0

        LMD = FileDateTime(MyPath & MyFile)

        If LMD > LatestDate Then
            LatestFile = MyFile
            LatestDate = LMD
        End If

        MyFile = Dir
    Loop
'*************读取TXT中的密码*************
    FileNum = FreeFile()
    Open PwdPath For Input As #FileNum
    ' 读取TXT第一行内容作为密码
    Line Input #FileNum, ReadPwd
    Close #FileNum
    ' 去除密码前后可能存在的空格、换行符
    ReadPwd = Trim(ReadPwd)

'*************使用读取到的密码打开文件*************
    Workbooks.Open MyPath & LatestFile, Password:=ReadPwd
 
End Sub

注意事项

  • 密码TXT文件建议设置对应操作系统级的访问权限,仅允许运行宏的账号读取,避免密码泄露
  • 如果密码存储在TXT的非第一行,可调整Line Input的读取次数,或者直接读取全部文本后提取密码
  • 如果需要后续复制数据到当前宏文件,可以在打开目标文件后,添加对应工作表数据复制的逻辑即可

内容的提问来源于stack exchange,提问作者Atul Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:15:04