Tôi đang tìm cách chạy macro, hãy gọi Macro01 từ WorkSheet01 trên WorkSheet02.Chạy Macro Excel qua C#: Chạy macro từ sổ làm việc này sang sổ làm việc khác?
Sử dụng Microsoft.Office.Interop.Excel Namespace Tôi đã mở một WorkSheet01.
public void Main_CodedStep()
{
// Object for missing (or optional) arguments.
object oMissing = System.Reflection.Missing.Value;
// Create an instance of Microsoft Excel
Excel.ApplicationClass oExcel = new Excel.ApplicationClass();
// Make it visible
oExcel.Visible = true;
// Open Worksheet01.xlsm
Excel.Workbooks oBooks = oExcel.Workbooks;
Excel._Workbook oBook = null;
oBook = oBooks.Open("C:\\Users\\Admin\\Documents\\Worksheet01.xlsm", oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
}
Sau đó, tôi sử dụng tập lệnh tự động để lấy báo cáo. Báo cáo này được mở qua lời nhắc tải xuống của IE và không phải là Interop.
vấn đề này được đưa ra khi tôi cố gắng để chạy các macro qua C# (Tôi đã thực hiện một Excel.ApplicationClass mới(); chỉ nên biên soạn, tôi tin rằng đây là một trong những sai lầm của tôi.)
public void FirstMacro_CodedStep()
{
// Create an instance of Microsoft Excel
Excel.ApplicationClass oExcel = new Excel.ApplicationClass();
Console.WriteLine("ApplicationClass: " + oExcel);
// Run the macro, "First_Macro"
RunMacro(oExcel, new Object[]{"Worksheet01.xlsm!First_Macro"});
//Garbage collection
GC.Collect();
}
private void RunMacro(object oApp, object[] oRunArgs)
{
oApp.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, oApp, oRunArgs);
}
Khi phương pháp này chạy nó chạy macro từ Worksheet01 trên Worksheet01 thay vì Worksheet02. Ngoài ra, nó đang tìm kiếm bảng tính trong My Documents nên tôi đã chuyển nó sang để xem điều gì sẽ xảy ra.
Tóm tắt:
- mở Worksheet01
- Via kịch bản nhận được và mở một báo cáo (Worksheet02) từ MSIE
- Run Macro01 từ Worksheet01 trên Worksheet02
Resources:
http://support.microsoft.com/kb/306683
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.aspx
Đối với những người muốn thử nó thêm video này vào sử dụng của bạn dùng các directives:
using System.Reflection;
using Microsoft.Office.Core; //Added to Project Settings' References from C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14 - "office"
using Excel = Microsoft.Office.Interop.Excel; //Added to Project Settings' References from C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14 - "Microsoft.Office.Interop.Excel"
Vui lòng kiểm tra này một http://stackoverflow.com/questions/27166341/run-microsoft-office-macro-using-c-sharp –