0

I'm really new to VBA (10 hours) coming from a bit of a Python background. Is there a VBA equivilant to Python when it comes to indexing part of a returned function? This is what I mean: If I have VBA code that looks like this:

Split(Worksheets("range").Range("K2").Offset(i, 0), "-", "-1")

And I only want the third part of the split, how would I get just that to output?

I imagine this is a really simple question but I can't seem to think it through. Thanks in advance!

1
  • Split(Worksheets("range").Range("K2").Offset(i, 0), "-", "-1")(2) would work with the default Option Base 0 setting, but as others have noted this might raise an error if there's no theird element in the array. Commented May 8, 2013 at 16:34

2 Answers 2

1

If this function is setting the value of a variant/array variable, e.g.,:

Dim myArray as Variant
myArray = Split(Worksheets("range").Range("K2").Offset(i, 0), "-", "-1")

Then you should be able to refer to the 3rd item in the array like:

Debug.Print myArray(2) 'Option Base 0 -- Default'

Or, if you have Option Base 1 then:

Debug.Print myArray(3)

Those examples use a constant expression (2 or 3) to index the array item. You could also use the match function to return a dynamic value, e.g., let's say you are looking for the value of "Steve" in this array:

Dim aItem as Long
aItem = Application.Match("Steve", myArray, False)

This returns a long/integer which you could then reference like:

Debug.Print myArray(aItem)

Cheers!

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

Comments

0

Something like:

Dim splitArr() as String, Counter as Long
Dim textString as String
textString = Worksheets("range").Range("K2").Offset(i, 0).Value2


splitArr = split(textString,"-",-1)
For cntr = LBound(splitArr) To UBound(splitArr)
    'here you can process splitArr(cntr)
Next cntr

' Just accessing the third element can be done by accessing splitArr(LBound(splitArr)+2)

Note that depending on your settings Arrays in VBA an start either from 0 or from 1, the above code works in either case. Also note that you probably would need to catch of errors / would end up with an unitialized array if the string is empty.

Comments

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.