1

I have the following code to retrieve a selection then making it a array of string.

Dim strArgument As Variant
Dim irange As Range
Dim ricosString As Variant

Set irange = Selection
ricosString = RangeToStringArray(irange)

Dim vArray As Variant
For i = LBound(ricosString) To UBound(ricosString)
    Set vArray = ricosString(i)

My problem here is on the ricosString(i). It is throwing an error Subscript out of range. Any ideas why?

Here is the code for RangeToStringArray

Public Function RangeToStringArray(theRange As Excel.Range) As String()

Dim variantValues As Variant
variantValues = theRange.Value

Dim stringValues() As String
ReDim stringValues(1 To UBound(variantValues, 1), 1 To UBound(variantValues, 2))

Dim columnCounter As Long, rowCounter As Long
For rowCounter = UBound(variantValues, 1) To 1 Step -1
   For columnCounter = UBound(variantValues, 2) To 1 Step -1
       stringValues(rowCounter, columnCounter) = CStr(variantValues(rowCounter, columnCounter))
   Next columnCounter
Next rowCounter

RangeToStringArray = stringValues

End Function

3 Answers 3

1

RangeToStringArray is 2 dimensional but you reference it as 1 dimensional Set vArray = ricosString(i)

Also Ricostring is not an object so you should not use Set

Sign up to request clarification or add additional context in comments.

Comments

0

Regarding that RangeToStringArray function, I don't really see its interest: why don't you just use ricosString = irange, which would be simpler and faster?

Comments

0

Define your ricosString as a proper String Array:

Dim ricosString() As String

Replace your RangeToStringArray Function with a proper one:

Public Function RangeToStringArray(theRange As Excel.Range) As String()

Dim cell As Range
Dim values() As String
Dim i As Integer

i = 0

ReDim values(theRange.Cells.Count)

For Each cell In theRange

    values(i) = cell.Value
    i = i + 1
Next cell

RangeToStringArray = values
End Function

Then you can refer to the values in the array like this:

vArray = ricosString(i) 'without Set

4 Comments

When I changed the RangeToStringArray function, it is erroring on the line For i = LBound(ricosString) To UBound(ricosString)
Subscript out of range.
How are you looping on the array ricosString?
For i = LBound(ricosString) To UBound(ricosString) Step 1 | i is defined as an Integer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.