C# 调用word时,禁用宏

10 篇文章 1 订阅

问题:

由于文档中有宏代码且有问题,导致打开文档时弹出vba错误提示框,致使代码阻塞

解决:

c#

static void Main(string[] args)
{
    Console.WriteLine("word文件:");
    var file = Console.ReadLine();
    Application app = null;
    Document doc = null;
    try
    {
        app = new Microsoft.Office.Interop.Word.ApplicationClass();
        // 屏蔽宏
        app.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable;
        doc = app.Documents.Open(file);
        doc.SaveAs(file + ".html", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML);
    }
    finally
    {
        doc.Close();
        app.Quit();
    }
}

powershell:

$Word=NEW-Object –ComObject Word.Application;
# $Word.WordBasic.DisableAutoMacros(1); 使用这个也可以
$Word.AutomationSecurity=3;
$Document=$Word.documents.open("d:\1.doc");
$Document.Close();
$Word.Quit();

MsoAutomationSecurity enumeration (Office)

NameValueDescription
msoAutomationSecurityByUI2Uses the security setting specified in the Security dialog box.
msoAutomationSecurityForceDisable3Disables all macros in all files opened programmatically without showing any security alerts.
msoAutomationSecurityLow1Enables all macros. This is the default value when the application is started.

参考:

https://docs.microsoft.com/zh-CN/office/vba/api/office.msoautomationsecurity

https://oomake.com/question/877535 

https://stackoverflow.com/questions/2846407/how-to-open-document-that-contains-autoopen-macro-with-powershell/3206081#3206081

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值