最近在研究C#调用Excel宏的功能,需要自动创建Excel的宏,如果表格中已经存在该名称的宏时再创建就会有问题!
请问有什么方法可以查找到表格中已存在的宏清单?请高手指教!!

解决方案 »

  1.   

    可以先清空宏,再建立转个例子:using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Reflection;
    using System.Text;
    using Office = Microsoft.Office.Core;
    using VBDE = Microsoft.Vbe.Interop;
    using Excel = Microsoft.Office.Interop.Excel;
    namespace ConsoleApplication1
    {class Class1
    {[STAThread]
    static void Main(string[] args)
    {
    string MyFile = Path.GetFullPath(".") + @"\sample.xls";
    CreateWorkbook(MyFile,GetMacro()); 
    Console.WriteLine("File Saved to " + MyFile);
    Console.ReadLine();
    }#region Get Macro
    private static string GetMacro()
    {
    StringBuilder sb = new StringBuilder();sb.Append("Sub FormatSheet()" + "\n");
    sb.Append(" msgbox \"http://www.cnblogs.com/huangcong/\"\r\n");
    sb.Append("End Sub");return sb.ToString();
    }
    #endregion#region Create Workbook
    private static void CreateWorkbook(string FileName,string Macro)
    {Excel.Application xl = null;
    Excel._Workbook wb = null;
    Excel._Worksheet sheet = null;
    VBDE.VBComponent module = null;
    bool SaveChanges = false;
    try
    {if (File.Exists(FileName)) { File.Delete(FileName); }GC.Collect(); xl = new Excel.Application();
    xl.Visible = false;wb = (Excel._Workbook)(xl.Workbooks.Add( Missing.Value ));
    sheet = (Excel._Worksheet)wb.ActiveSheet;module = wb.VBProject.VBComponents.Add(VBDE.vbext_ComponentType.vbext_ct_StdModule);
    module.CodeModule.AddFromString(Macro);xl.Visible = false;
    xl.UserControl = false;
    SaveChanges = true;wb.SaveAs(FileName,Excel.XlFileFormat.xlWorkbookNormal,
    null,null,false,false,Excel.XlSaveAsAccessMode.xlShared,
    false,false,null,null,null);}
    catch( Exception theException ) 
    {
    String msg;
    msg = "Error: ";
    msg = String.Concat( msg, theException.Message );
    msg = String.Concat( msg, " Line: " );
    msg = String.Concat( msg, theException.Source ); 
    Console.WriteLine(msg);
    }
    finally
    {try
    {
    xl.Visible = false;
    xl.UserControl = false;
    wb.Close(SaveChanges,null,null);
    xl.Workbooks.Close();
    }
    catch { }xl.Quit();if (module != null) { Marshal.ReleaseComObject (module); }
    if (sheet !=null) { Marshal.ReleaseComObject (sheet); }
    if (wb !=null) { Marshal.ReleaseComObject (wb); }
    if (xl !=null) { Marshal.ReleaseComObject (xl); }module = null;
    sheet=null;
    wb=null;
    xl = null;
    GC.Collect(); 
    }}
    #endregion
    }
    }原文地址
      

  2.   

    这个是新建Excel再创建宏的例子,我要实现的是在已存在的Excel文件下操作;而且我现在的Excel表格中已经存在很多个宏,清空再建的方法也不可行!不过还是谢谢提供宝贵意见!