3

我有一个 Excel 电子表格,它位于用 C# 编写的自动化测试应用程序中。测试应用程序使用最终统计数据填充工作表,然后使用电子表格生成指标。该过程的一部分是将下拉列表放入电子表格的 L 列,并将其关联的 VBA 更改事件从应用程序写入工作表中。

这是将下拉列表写入电子表格 Excel.DropDown xlDropDown 的代码;

//set range for insert cell
 range = wrkSheet.get_Range("L" + (x + 9).ToString() + ":L" + (x + 9).ToString());

//insert the dropdown into the cell
xlDropDown = xlDropDowns.Add((double)range.Left, (double)range.Top, (double)range.Width, (double)range.Height, true);

//set the nbame of the new dropdown
xlDropDown.Name = "expFail" + (x + 1).ToString();

//assign dropdown name to cmbName 
cmbName = xlDropDown.Name;

 //call function to write change macro for this box 
 cmbWriteMacro(cmbName, xlApp, xlBook, wrkSheet); 

cmbWrite 函数:

    StringBuilder sb;
    VBA.VBComponent xlModule;
    VBA.VBProject prj;
    string modName;
    int modExists;

    prj = wrkBook.VBProject;
    modExists = 0;

    sb = new StringBuilder();

    //build string with module code 
    sb.Append("Sub " + cmbName + "_Change()" + "\n");
    sb.Append("\t" + "Call lstBox_Update(" + cmbName + ")" + "\n");
    sb.Append("End Sub");

    foreach (VBA.VBComponent comp in prj.VBComponents)
    {
        modName = comp.Name;

        if (modName == "Module2")
        {
            modExists = 1;
            break;
        }
    }

     //check to see if module already exists
     if (modExists != 1)
     {
        //set an object for the new module to create
        xlModule = wrkBook.VBProject.VBComponents.Add(VBA.vbext_ComponentType.vbext_ct_StdModule);
     }
     else
     {
        xlModule = wrkBook.VBProject.VBComponents.Item("Module2");
     }

     //add the cmbbox macro to the spreadsheet
     xlModule.CodeModule.AddFromString(sb.ToString());

这会将以下 VBA 事件写入电子表格,以便在记录失败时在工作表中执行操作。

Sub expFail1_Change(ByVal Target As Range)
    Call lstBox_Update("expFail1")
End Sub

所有下拉菜单都会根据选择的内容调用相同的函数 (lstBox_Update)。

一切正常。下拉菜单显示在它们应该出现的位置,并且宏正在正确地写入电子表格中。问题似乎是在更改选择时触发相关的更改事件。解决方案可能很简单,但我已经看了一遍,似乎找不到答案

4

3 回答 3

1

I just did a small example based on your code. After some googling around and testing some source code pieces it comes down to a single line of code:

xlDropDown.Name = "expFail" + (x + 1).ToString(); // your code
xlDropDown.OnAction = xlDropDown.Name + "_Change"; // new code: IMPORTANT

Found this code within an Microsoft KB article How To Create an Excel Macro by Using Automation from Visual C# .NET.

It seems that you need this line of code to set some kind of delegate pointing to your custom vba code.

In case you need my complete source let me know and I will mail it to you.

于 2013-02-13T21:05:31.807 回答
0

您必须将更改事件写入创建组合框的工作表(而不是 VBA 模块“module2”。组合框是工作表(对象)的一部分,所有事件处理程序都必须在那里。

于 2013-02-13T16:10:31.843 回答
0

根据这篇文章,您需要将代码写入Worksheet_Change事件,而不是ComboBox_Change事件:

Sub Worksheet_Change(ByVal Target As Range)
    Call lstBoxUpdate("expFail1")
End Sub
于 2013-02-13T16:20:37.637 回答