我有一個 VSTO 代碼,它呼叫加載到 VSTO 功能區標題上的 VBA 代碼。我想知道您是否可以(以及如何)將 VBA 代碼中的值寫入 VSTO 作業簿。我在下面附上了我的代碼。
using Microsoft.Office.Tools.Ribbon;
using System;
using Excel = Microsoft.Office.Interop.Excel;
namespace Isitpossible
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void callVBA_Click(object sender, RibbonControlEventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
String FilenamePath;
FilenamePath = "C:\Test\MyWorkbook.xlsm"; //Where the workbooks where all the marco are stored
//~~> Start Excel and open the workbook.
xlWorkBook = xlApp.Workbooks.Open(FilenamePath,0, true);
xlApp.Visible = false;
//~~> Run the macros by supplying the necessary arguments
xlApp.Run("Test");
}
}
}
我的 VBA 子程式寫在這里:
Sub Test()
ActiveWorkbook.ActiveSheet.Range("C1").Value = "This Works!"
End Sub
uj5u.com熱心網友回復:
首先,無需從您的 VSTO 加載項創建新的應用程式實體:
Excel.Application xlApp = new Excel.Application();
要訪問宿主應用程式的物件模型,請使用類的Application欄位ThisAddIn。此欄位回傳一個表示主機應用程式當前實體的物件。在 MSDN 上的訪問主機應用程式的物件模型部分了解更多資訊。
因此,您的代碼應如下所示:
private void callVBA_Click(object sender, RibbonControlEventArgs e)
{
Excel.Workbook xlWorkBook;
String FilenamePath;
FilenamePath = "C:\Test\MyWorkbook.xlsm"; //Where the workbooks where all the marco are stored
//~~> Start Excel and open the workbook.
xlWorkBook = Application.Workbooks.Open(FilenamePath,0, true);
xlApp.Visible = false;
Application.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityLow;
//~~> Run the macros by supplying the necessary arguments
xlApp.Run("Test");
}
有關詳細資訊,請參閱從 C# 運行宏。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/407226.html
標籤:
