There are similar questions about passing parameter arrays and they work within managed code. When working with Microsoft.Office.Interop.Excel you can run a macro in an Excel file with the Application.Run method. The signature of the method shows that it takes a macro name, and an arbitrary list of arguments that get passed to the Excel VBA Procedure. This looks and behaves like a Parameter array but it is not.
When you pass a parameter array to the argument section of .Run you get:
System.Runtime.InteropServices.COMException: 'Parameter not optional. (Exception from HRESULT: 0x8002000F (DISP_E_PARAMNOTOPTIONAL))'
Which suggests that the Parameter Array is not getting passed correctly, likely due to COM interop not having a ParamArray type.
How would I expand my arbitrary length ParamArray into an arbitrary list of arguments that can be passed to the COM object?
EXAMPLE CODE:
''' <summary>
''' Run an Excel macro silently in the background. Quits at the end.
''' </summary>
''' <param name="excelFileName">Full path to Excel file.</param>
''' <param name="macroName">The macro you want to run.</param>
''' <param name="args">Arguments to pass into that macro procedure.</param>
Public Shared Sub RunMacro(excelFileName As String, macroName As String, ParamArray args As String())
' Create new Excel instance
Dim excelApp = New Application With {
.Visible = True,
.EnableEvents = False ' Suppress the Workbook_Open event
}
Dim excelBooks As Workbooks = excelApp.Workbooks
' Open the Excel workbook
Dim thisWorkbook As Workbook = excelBooks.Open(excelFileName)
' Hide the window while the macro runs
excelApp.Visible = False
' Run the VBA procedure.
excelApp.Run(macroName, args) ' <-- Throws because it can't accept ParamArray
' Cleanup
thisWorkbook.Close(SaveChanges:=False)
excelApp.Quit()
End Sub
Sub/Functionnamed asmacroNamehaving a singleParamArray()parameter, you cannot call it passing an array. Even if you pseudo declare it asParamArray(). Not only through a COM interop. You cannot do it in Excel VBA, neither. In VBA,ParamArray()is used only to pass an undefined number of parameters/types. But you must call the function using all these parameters!. If you want passing an array, do it, but not declaring as 'ParamArray()` and declaring in the called subarr () As Variant.ParamArray()only as a called Sub/function last parameter. And does that only to allow an undefined number of arguments/types when make the call, as stated above... Please, see here...