从C#运行VBA宏时,ActiveWorkbook无效

时间:2018-02-16 22:07:56

标签: c# excel-vba office-interop vba excel

我正在尝试编写一个Winform应用程序并将Excel作为控件停靠在其中。一切正常,直到我尝试从我的c#app运行Excel宏(用VBA编写)。当 此宏 尝试访问ActiveWorkBook时,它就是Nothing。

有趣的是,如果我注释掉“SetParent(xlHwnd,this.Handle);”,则可以使用ActiveWorkBook。好像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");

   }

}

1 个答案:

答案 0 :(得分:0)

根据MSDN,您必须在宏中使用ThisWorkbook而不是ActiveWorkbook,因为这是包含宏的那个。

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