Home » excel » Excel VBA Passing Range to Function yields 424: Object Required

Excel VBA Passing Range to Function yields 424: Object Required

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to pass a range to a function and getting Run-time error 424: Object required.

Here is the function:

Function TextToCol(myRange As Range)

    myRange.TextToColumns Destination:=myRange, DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
    Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
    :=Array(1, 1), DecimalSeparator:=".", ThousandsSeparator:=",", _
    TrailingMinusNumbers:=True

End Function

And here is the sub where I’m trying to use it:

Sub Test()

    Dim wschar              As Worksheet
    Dim rng                 As Range

    Set wschar = ThisWorkbook.Worksheets("Charges")

    Set rng = wschar.Range("A1")

    TextToCol (rng)

End Sub

I’ve tried this several different ways and can’t figure out why it won’t accept my range.

This is the line it highlights in yellow as not passing:

TextToCol (rng)
How to&Answers:

Remove the parenthesis in TextToCol (rng) & Good luck with the further debugging.


In general, it is considered that functions should return something (Text, Value or Object), otherwise Sub should be used. In your case, consider writing Sub TextToCol(myRange As Range).


ByRef and ByVal are somehow tricky in VBA, here you can see some examples of it:

Public Sub TestMe()

    Dim var1, var2
    Dim var3, var4
    Dim var5, var6        
    var1 = Array(1, 1)
    var2 = Array(2, 1)
    var3 = Array(3, 1)
    var4 = Array(4, 1)
    var5 = Array(5, 1)
    var6 = Array(6, 1)

    increment1 (var1)
    increment2 (var2)
    increment1 var3
    increment2 var4
    var5 = increment1(var5)
    var6 = increment2(var6)

    Debug.Print var1(0)
    Debug.Print var2(0)
    Debug.Print var3(0)
    Debug.Print var4(0)
    Debug.Print var5(0)
    Debug.Print var6(0)

End Sub    

Public Function increment1(ByVal testValue As Variant) As Variant
    testValue(0) = testValue(0) + 100
    increment1 = testValue
End Function    
Public Function increment2(ByRef testValue As Variant) As Variant
    testValue(0) = testValue(0) + 100
    increment2 = testValue
End Function

Printing:

 1 
 2 
 3 
 104 
 105 
 106