从C#运行VBA宏时,ActiveWorkBook一无所有



我正在尝试编写一个winform应用程序,并将其登上它作为控件。一切都起作用,直到我尝试从C#应用程序运行Excel宏(用VBA编写(。当此宏尝试访问ActiveWorkbook,这是什么。

有趣的是,如果我评论" setparent(xlhwnd,this.handle(";似乎Excel应用程序的窗口状态正在影响当前的ActiveWorkbook。

以下是我的代码:

xlApp = newMicrosoft.Office.Interop.Excel.Application();
xlApp.WindowState = XlWindowState.xlMinimized;
xlApp.DisplayFormulaBar = false;
xlApp.ShowWindowsInTaskbar = false; 
xlApp.DisplayAlerts = false;
xlApp.DisplayStatusBar = false;
xlApp.Interactive = true;
xlApp.Visible = true;
xlHwnd = (IntPtr)xlApp.Hwnd;
//Windows API call to change the parent of the target window.
SetParent(xlHwnd, this.Handle);
//Wire up the event to keep the window sized to match the control
SetWindowPos(xlHwnd, 0, this.DisplayRectangle.Left, this.DisplayRectangle.Top, this.DisplayRectangle.Width, this.DisplayRectangle.Height, 0X0040 | 0X4);
this.SizeChanged += newEventHandler(Panel1_Resize);
xlWorkbook = xlApp.Workbooks.Add();            
vardbAddIn = (AddIn)xlApp.AddIns[3];            
if(dbAddIn != null)
{
   WorkbookdbWorkbook = xlApp.Workbooks.Open(dbAddIn.FullName);
   if(dbWorkbook != null)
   {
          dbWorkbook.Application.Run("myMacro1");
   }
}

根据MSDN,您必须在宏中使用此Workbook而不是ActiveWorkbook,因为这是包含宏的

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-thisworkbook-property-excel

最新更新