zl程序教程

您现在的位置是:首页 >  工具

当前栏目

VBA: 打开带密码的Excel文件

2023-06-13 09:12:58 时间

文章背景:想要通过VBA打开一份带密码的Excel文件,然后在文件内填入信息。前述要求可以借助workbook.open来实现。

1. Workbooks.Open 介绍

功能:Opens an existing workbook and adds it to the Workbooks collection . Returns a reference to the workbook that was opened.

语法:workbooks.Open(Filename, [UpdateLinks], [ReadOnly], [Format], [Password], [WriteResPassword], [IgnoreReadOnlyRecommended], [Origin], [Delimiter], [Editable], [Notify], [Converter], [AddToMru], [Local], [CorruptLoad])

  • Filename 要打开的工作簿的文件名。
  • UpdateLinks 数值为0,代表工作簿打开时不更新外部引用(链接)。
  • ReadOnly 如果为 True,则以只读模式打开工作簿。
  • Format 如果 Microsoft Excel 打开文本文件,则由此参数指定分隔符。数值为5,表示没有分隔符。
  • Password 一个字符串,包含打开受保护工作簿所需的密码。
  • WriteResPassword 一个字符串,包含写入受保护工作簿所需的密码。

2. 示例代码

通过VBA实现的功能:打开带密码的Excel文件,并在文件内填入信息。

Option Explicit

Sub test()

    '打开带密码的excel文件
    
    Dim xlapp1 As Excel.Application
    Dim xlbook1 As Excel.Workbook
    Dim xlsheet1 As Excel.Worksheet
    
    Dim path As String
    
    Dim row_final As String
    
    path = "E:\工作\报告展示\测试文件_密码123.xlsm"
    
    If fileExist(path) Then
            
        Set xlapp1 = CreateObject("Excel.Application")
        Set xlbook1 = xlapp1.Workbooks.Open(path, 0, False, 5, "123", "123")
        Set xlsheet1 = xlbook1.Worksheets(1)
            
        row_final = xlsheet1.Range("A65535").End(xlUp).Row
                
        xlsheet1.Cells(row_final + 1, 1) = "2021/11/6"         '日期
   
        xlbook1.Close savechanges:=True
        xlapp1.Quit '关闭测试数据工作簿
    
        Set xlapp1 = Nothing
        
        MsgBox "Done!"
                
    Else
            
        MsgBox "文件路径不存在:" & path & vbCrLf & vbCrLf & "请确认!"
            
    End If
    
End Sub

Function fileExist(path As String) As Boolean

    '判断指定路径的文件是否存在
    
    Dim sName As String
    
    sName = Dir(path)
    
    If Len(sName) Then
    
        fileExist = True
        
    Else
    
        fileExist = False
    
    End If
    
End Function

视频演示:http://mpvideo.qpic.cn/0bc3xqabeaaammalfdugcvqvbpgdck6aaeqa.f10002.mp4?dis_k=91444e260752b69988a72c74a76ae04e&dis_t=1663656065&vid=wxv_2124342637947158530&format_id=10002&support_redirect=0&mmversion=false

参考资料:

[1] Workbooks.Open(https://www.oreilly.com/library/view/programming-excel-with/0596007663/re315.html)

[2] EXCEL-VBA:Workbooks.Open 参数 (打开文件)(https://blog.csdn.net/jyh_jack/article/details/83820068)

[3] VBA 打开带密码的文件(https://blog.csdn.net/weixin_33709590/article/details/94254831?spm=1001.2101.3001.6650.10&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-10.highlightwordscore&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-10.highlightwordscore)