Use C # To create a personal macro workbook for Excel

Source: Internet
Author: User

In the past, I used C # To directly operate Excel, but found that the performance was extremely low. Recently, I found that using macros in Excel can quickly complete the batch processing function, so I decided to write a program using C # To create a macro for an Excel file. The project is as follows:


 

Code
 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()" + "");
sb.Append(" msgbox "http://www.cnblogs.com/huangcong/"");
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( Missin

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.