【发布时间】:2010-09-08 03:53:20
【问题描述】:
是否可以使用 API 从 Word 2007“docm”文档中提取所有 VBA 代码?
我找到了如何在运行时插入 VBA 代码,以及如何删除所有 VBA 代码,但没有将实际代码提取到我可以存储的流或字符串中(并在将来插入到其他文档中)。
任何提示或资源将不胜感激。
编辑:感谢大家,Aardvark 的答案正是我想要的。我已将他的代码转换为 C#,并且能够使用 Visual Studio 2008 从类库中调用它。
using Microsoft.Office.Interop.Word;
using Microsoft.Vbe.Interop;
...
public List<string> GetMacrosFromDoc()
{
Document doc = GetWordDoc(@"C:\Temp\test.docm");
List<string> macros = new List<string>();
VBProject prj;
CodeModule code;
string composedFile;
prj = doc.VBProject;
foreach (VBComponent comp in prj.VBComponents)
{
code = comp.CodeModule;
// Put the name of the code module at the top
composedFile = comp.Name + Environment.NewLine;
// Loop through the (1-indexed) lines
for (int i = 0; i < code.CountOfLines; i++)
{
composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine;
}
// Add the macro to the list
macros.Add(composedFile);
}
CloseDoc(doc);
return macros;
}
【问题讨论】:
-
使用StringBuilder优化内存使用:StringBuilder sb = new StringBuilder(); for.... sb.AppendLine("你的代码行"); ... 宏.Add(sb.ToString());
标签: .net automation ms-office