不能将c# int数组传递给VBA Excel宏

本文关键字:VBA Excel int 数组 不能 | 更新日期: 2023-09-27 17:49:23

我正在尝试调用我的Excel工作表(2003)宏从我的c#应用程序与c#互操作。

在整型参数之前工作得很好。但是现在我需要传递一个整数数组,我一直得到一个类型不匹配异常。

COMException: Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
c#代码是这样的:
object m = Type.Missing;    
xlApp.Run("MergeColumnsKeepValues", lastGroupRowExcel, firstGroupRowExcel, mergeColumns, rightFormatMergeColumn,
                        multiRowColumn, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m, m);

mergeColumnsInt32[9]外,其余参数均为Int32类型

我的Excel模板中的VBA宏看起来像这样:

Sub MergeColumnsKeepValues(lastGroupRow As Integer, firstGroupRow As Integer, mergeColumns() As Variant, helpColumnMerge As Integer, multiRowColumn As Integer)
    ... <- no use of array, just declaring variables and stuff
    Dim i As Integer
    For i = LBound(mergeColums) To UBound(mergeColumns)
        Set targetMergeCells = Range(Cells(firstGroupRow, mergeColumns(i)), Cells(lastGroupRow, mergeColumns(i)))
        Call targetMergeCells.PasteSpecial(xlPasteFormats, xlPasteSpecialOperationNone, False)
    Next
End Sub

我尝试在VBA中声明数组ByRef,我尝试将其声明为Variant数组,但没有任何改变。我尝试在开始处放置MsgBox,以查看不匹配是否发生在循环或参数级别,并且它不显示MsgBox。有人知道如何解决这个问题或原因是什么吗?

不能将c# int数组传递给VBA Excel宏

我试过了

static void Main(string[] args)
        {
            XL.Application xlapp = new XL.Application();
            xlapp.Visible = true;
            xlapp.Workbooks.Open("c:/test/test_c.xlsm");
            int[] x = new int[] { 1, 2, 3, 4 };
            xlapp.Run("MergeColumnsKeepValues", x, 2, 3, 4,5);
        }

按如下方式调用VBA

Public Sub MergeColumnsKeepValues(ByRef lastGroupRow As Variant, _
                                    firstGroupRow As Integer, _
                                    mergeColumns As Integer, _
                                    helpColumnMerge As Integer, _
                                    multiRowColumn As Integer)
    MsgBox "Hello"
End Sub