Excel精英培训网

 找回密码
 注册
数据透视表40+个常用小技巧,让你一次学会!
查看: 9812|回复: 2

[分享] 通过修改注册表改变Excel的宏安全级别设置

[复制链接]
发表于 2011-7-29 08:48 | 显示全部楼层 |阅读模式
本帖最后由 glhfgtd 于 2011-7-29 08:48 编辑

通过对HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Excel\Security\Level的更改是可以改变Excel的宏安全的,只是必须重新启动Excel程序才能生效。

Option Explicit
Sub SetExcelVBA()
'功能:改变Excel的安全级别
'使用:WscriptFileSystemObject,创建txt文件,注册表操作,VBS文件自我删除,改变Excel文件读写属性等

Dim WSH As Object, ret As String, regStr As String
Dim strFullname As String, strVBS As String
Dim tf, fso, RetVal
'本程序仅适用于Excel2003( 11.0),如果当前版本不是2003则退出
If Application.Version <> "11.0" Then MsgBox"本代码仅在 Excel 2003 下可使用! ", vbOKOnly +vbCritical, "Keanjeason": Exit Sub
strFullname = ThisWorkbook.FullName '取得当前工作薄的全名
strVBS = Replace(UCase(strFullname), ".XLS",".vbs") 'temp文件VBS的文件名
Set WSH = CreateObject("Wscript.Shell") '创建Wscript对象
Err.Clear
On Error Resume Next
regStr ="HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Excel\Security\Level"'注册表中Excel vba安全级别位置
ret = WSH.RegRead(regStr) '读取当前安全级别
If Err.Number <> 0 Then

'判断读取是否成功

MsgBox "从注册表读取当前Excel VBA安全级别设置失败,本程序将退出! ",vbOKOnly + vbCritical, "Keanjeason"

Exit Sub
Else

'如果当前Excel VBA安全级别不为“低”,则设置为“低”,1-4分别对应:低,中,高,非常高

If Val(ret)<> 1 Then ret = WSH.RegWrite(regStr, "1","REG_DWORD")
End If
Set fso =CreateObject("Scripting.FileSystemObject")
Set tf = fso.CreateTextFile(strVBS, True) '创建temp文件VBS文件
With tf

'写入VBS文件内容

.WriteLine("Dim oExcel,fso,delme")

.WriteLine("Set fso =CreateObject(""Scripting.FileSystemObject"")")

.WriteLine("Set oExcel =CreateObject(""excel.application"")")

.WriteLine("oExcel.Workbooks.Open " & Chr(34) & strFullname &Chr(34))

.WriteLine("oExcel.Visible=true")

.WriteLine("Set oExcel = Nothing")

.WriteLine("delme = fso.DeleteFile(" & Chr(34) & strVBS & Chr(34)& ")")

.Close
End With
With ThisWorkbook

'将当前文件属性设置为“只读”,以方便重新打开

.ChangeFileAccessMode:=xlReadOnly

.Saved = True
End With
RetVal = WSH.Run(Chr(34) & strVBS & Chr(34), 1,True) '运行刚刚创建的VBS文件,新启动一个Excel程序
Application.Quit '退出当前Excel
Set WSH = Nothing
Set fso = Nothing
End Sub

excel精英培训的微信平台,每天都会发送excel学习教程和资料。扫一扫明天就可以收到新教程
发表于 2011-7-29 18:06 | 显示全部楼层
回复

使用道具 举报

发表于 2011-7-29 18:53 | 显示全部楼层
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|Excel精英培训 ( 豫ICP备11015029号 )

GMT+8, 2024-5-6 17:33 , Processed in 0.601949 second(s), 3 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表