Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ParamArray correctly with class

Tags:

vba

I have a class ReportError:

Option Explicit
Public ID As String
Public bookType As String
Public msg As String
Public sheetName As String
Public c As Long
Public r As Long
Private pValues() As Variant
Public Property Get Values() As Variant()
    Values = pValues
End Property
Public Property Let Values(ByRef arr() As Variant)
    pValues = arr
End Property

And Sub CreateErrorForReport:

Public Sub CreateErrorForReport(ByVal errID As String, ByVal errSheetName As String, ByVal errRow As Long, ByVal errCol As Long, ParamArray Fields() As Variant)
    Dim shtSource As Worksheet
    Dim i As Long, row As Long
    Dim err As New ReportError
    Set shtSource = Worksheets(ERR_WS_NAME)

    If UBound(Fields) >= LBound(Fields) Then
            err.Values = Fields  
    End If

    error_index = error_index + 1
    errorDict.Add error_index, err
End Sub

In my main module I have a row

CreateErrorForReport "010", ws.Name, i, 15, 16, 17, 18, 19, 20

But get a "type mismatch" error on row

err.Values = Fields

How to add param array fields to object property values correctly?

like image 821
Alexey C Avatar asked Dec 06 '25 03:12

Alexey C


1 Answers

Use only Variant type not Variant() array type.
The varbu variable will contain the paramarray and assign it to the class property.

Option Explicit
Public ID As String
Public bookType As String
Public msg As String
Public sheetName As String
Public c As Long
Public r As Long
Private pValues As Variant
Public Property Get Values() As Variant
    Values = pValues
End Property
Public Property Let Values(arr As Variant)
    pValues = arr
End Property

Public Sub CreateErrorForReport(ByVal errID As String, ByVal errSheetName As String, ByVal errRow As Long, ByVal errCol As Long, ParamArray Fields() As Variant)
    Dim shtSource As Worksheet
    Dim i As Long, row As Long
    Dim err As New ReportError
    Set shtSource = Worksheets(ERR_WS_NAME)

    If UBound(Fields) >= LBound(Fields) Then
            varbu = Fields
            err.Values = varbu
    End If

    error_index = error_index + 1
    errorDict.Add error_index, err
End Sub



Later in the Sub you can refer to an element with e.g. err.Values(2)

like image 133
Black cat Avatar answered Dec 08 '25 20:12

Black cat