简体   繁体   中英

vba excel - How to delineate a cell with multiple times in it?

I am writing a macro to separate some data in one cell to multiple columns using the text to columns function. The problem I am running into is figuring out a way to separate a cell with multiple times in it, like so: "9:0011:008:0012:30". I would like to separate it out into: "9:00" "11:00" etc. If I separate by ":" I'm going to get 9, 00, 11, 00. If I do it by ":**" I'm only going to get 9, 11, 8, 12, cutting off the 12:30 time.

Thanks in advance!

This is my golf attempt:

Option Explicit

Public Sub TestMe()

    Dim strInput        As String
    Dim counter         As Long
    Dim strCurrent      As String

    strInput = "9:0011:008:0012:30"

    For counter = 1 To Len(strInput) - 2

        If Mid(strInput, counter, 1) = ":" Then
            Debug.Print strCurrent & Mid(strInput, counter, 3)
            counter = counter + 2
            strCurrent = vbNullString
        Else
            strCurrent = strCurrent & Mid(strInput, counter, 1)
        End If
    Next counter

End Sub

It nicely returns:

9:00
11:00
8:00
12:30

It assumes that the minutes are always with two digits. You can easily change it to a function, returning Array() .

The TextToColumns() function requires a Delimiter that is essentially "sacrificed", and you do not have one in those strings! Therefore, the TextToColumns() approach is not viable.

I suggest you use VBA string manipulation functions instead:

  1. Find the position of the first ":" in the string; call it "p"
  2. Extract your first item (the characters from the 1st to the p+2) into an output variable, call it x
  3. Remove the x from the original string
  4. Go to Step 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM