Atl*_*LED 18 c# vb.net excel vba vsto
我正在努力C#,现在VB.NET是旧VBA程序的端口.它有许多MSForms/OleObjects嵌入其中CommandButton甚至图像.
我的第一个想法是声明所有的按钮,Microsoft.Vbe.Interop.Forms.CommandButton但这导致了一个无法强制转换的COM异常.如果我尝试这个解决方案的更通用版本,我找不到任何项目,如果我尝试通过所有项目,我会注意到它们都是,但没有任何控件:System._COM type...Forms.CommandButtonVBComponetworkbook
foreach (VBComponent xxx in Globals.ThisWorkbook.VBProject.VBComponents) {
Interaction.MsgBox(xxx.Name);
Interaction.MsgBox(xxx.ToString);
}
Run Code Online (Sandbox Code Playgroud)
因此,所有这些控件的不是.VBComponets,但我可以找到为他们OLEobjects中thisworkbook.worksheets(n).OLEobjects(这是counterintutive给我,但我可能不了解系统开始).
如何处理来自此类对象的Click操作?
我假设我需要使用Excel.OLEObjectEvents_Event界面,但我似乎无法弄清楚如何.如果我尝试使用自定义事件delegates,我似乎无法将它们分配给OleObjects.如果我使用ActionClickEventHandler.CreateDelegate我可以得到各种各样的错误,这让我觉得这是一个死胡同.
在官方文件从MS似乎并不认为有帮助的,但它确实给我介绍的想法的Verb,我期待到.到目前为止,只会出现"应用程序无法启动"的错误.
即使只是尝试使用两个标准事件之一.GotFocus,我总是拉出0x80040200错误.例:
Excel.OLEObject ButtonCatcher = Globals.ThisWorkbook.Worksheets(1).OLEObjects("CommandButton1");
ButtonCatcher.GotFocus += CommandButton1_Click;
Run Code Online (Sandbox Code Playgroud)
Exception from HRESULT: 0x80040200在第二行引发COMException .该按钮已启用,我在查找Office开发站点的代码后查看了该按钮.
在包含控件的工作表的代码中尝试更通用的方法:
object CommandButtonStart = this.GetType().InvokeMember("CommandButton1", System.Reflection.BindingFlags.GetProperty, null, this, null);
Run Code Online (Sandbox Code Playgroud)
引发Missing Method错误.
非常感谢任何帮助,这似乎应该是显而易见的,我很想念它.
**编辑:我还发现我可以将这些控件转换为Excel.Shape但实际上并没有让我更接近于从VSTO运行函数或子函数.我正在玩,Excel.Shape.OnAction但这需要调用VBA子.据推测,只要VSTO是COM可见,我就可以调用VBA子调用VSTO中的sub.这似乎真的很圆润,我只想做它作为最后的手段.
解决方案类型: VSTO 文档级
场景:
1.) Excel.Worksheet 在运行时创建。(不是工作表宿主项)
2.) 在运行时在工作表上添加一个按钮,单击该按钮会触发 C# 代码。
程序集引用:
Microsoft.Vbe.Interop (Microsoft.Vbe.Interop.dll)
Microsoft.Vbe.Interop.Forms (Microsoft.Vbe.Interop.Forms.dll)
Microsoft.VisualBasic (Microsoft.VisualBasic.dll)
测试/工作代码:
using MSForms = Microsoft.Vbe.Interop.Forms;
using System.Windows.Forms;
...
Microsoft.Vbe.Interop.Forms.CommandButton CmdBtn;
private void CreateOLEButton()
{
Excel.Worksheet ws = Globals.ThisWorkbook.Application.Sheets["MyWorksheet"];
// insert button shape
Excel.Shape cmdButton = ws.Shapes.AddOLEObject("Forms.CommandButton.1", Type.Missing, false, false, Type.Missing, Type.Missing, Type.Missing, 500, 5, 100, 60);
cmdButton.Name = "btnButton";
// bind it and wire it up
CmdBtn = (Microsoft.Vbe.Interop.Forms.CommandButton)Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(ws, null, "btnButton", new object[0], null, null, null);
CmdBtn.Caption = "Click me!";
CmdBtn.Click += new MSForms.CommandButtonEvents_ClickEventHandler(ExecuteCmd_Click);
}
private void ExecuteCmd_Click()
{
MessageBox.Show("Click");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2439 次 |
| 最近记录: |