• Fun with Split() (VB6)

    Author
    Topic
    #424374

    Toying around with the Split() function, I stumbled upon a way to extract words from sentences. This method does not require any explicit use (even mention) of an array at all. I imagine the method could be useful in many situations e.g. extracting an entry from a CSV or other delimited text file.


    Sub SplitTest()
    Dim Sentence As String

    Sentence = "Alas, poor Yorick! I knew him, Horatio"
    Debug.Print Split(Sentence)(2) & " and " & Split(Sentence)(6)
    Debug.Print Split("Extract the third word in this sentence")(2)

    End Sub

    Output:
    Yorick! and Horatio
    third

    Alan

    Viewing 0 reply threads
    Author
    Replies
    • #974516

      Split returns a single dimension array, no matter how you use it. Here’s a variation that calls Split only once:

      Sub SplitTest()
      Dim Sentence As String
      Dim Words As Variant
      Sentence = “Alas, poor Yorick! I knew him, Horatio”
      Words = Split(Sentence)
      Debug.Print Words(2) & ” and ” & Words(6)

      End Sub

      • #974519

        Yep yep, that’s the “standard” documented usage of Split(). What I like about the method I found is that there is no need to Dim or name a variant (array) at all. Handy I’d think, for “one off” extractions of specific record fields etc. I don’t think it’s documented, but it is consistent with what you say i.e. Split returns a zero-based single dimension array.

        Alan

        • #974532

          Yes, but in

          Debug.Print Split(Sentence)(2) & ” and ” & Split(Sentence)(6)
          Debug.Print Split(“Extract the third word in this sentence”)(2)

          the VBA interpreter must execute the Split function three times. Split is calculation intensive and uses a lot of memory. If you declare a variant, Split only needs to be executed once.

          • #974580

            Yes, I realize the CPU/ memory implications. I was just pointing out what seems to be an undocumented syntax, possibly suited to a for “one off” usage, not requiring the explicit declaration of a variant (array). As always, it is up to the programmer to utilise the function judiciously.

            Alan

            • #974714

              For what it’s worth, I usually use split as an array as you have, but I’m usually only interested in one piece of a string.
              Don Ceraso first brought it to my attention in this puzzle thread started by Kevin.

            • #974721

              Thanks Sammy. You illustrate my point admirably wink. Looks like my “discovery” was only about 3 years late though. I seem to be improving. grin

              Alan

    Viewing 0 reply threads
    Reply To: Fun with Split() (VB6)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: