VBA如何打开带密码的Excel文件
1、在Excel文件中,同时按下组合按钮【alt+F11】,打开vba编辑器。
2、在编辑器窗口中,插入一个模块,然后在模块内输入如下代码。
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/7" '日期
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
3、运行上述的宏命令,就可以打开指定的带密码的Excel文件,并将日期添加到指定单元格内。