Need VBA, this one is a challenge

skyport

Active Member
Joined
Aug 3, 2014
Messages
374
Assuming source data are in cells in column A. Need to find all dates (format xx/xx/xx) in each of the cells in column A. Then choose only those dates that are proceeded by a comma then a space, no other dates to be included. Then place the LAST 10 characters proceeding the comma in a separate cell in column B and along side of that, the applicable date in column C. This should create a column in B of different 10 digit entries (one entry of 10 digits per each cell). Along side of that, there would be the list in column C of the dates.

Mr. Excel has never failed to find a solution for me in the past. My compliments always to those that help. Please help if you can. Thanks
 
Rick, once again you got the tiger by the tail here. The code functions in the proper direction for the purpose. The only detail is the one you raised above about multiple occurrences within the same source cells. The answer to that is yes, they are occurring multiple times within a cell. Great catch there on your part. If the code you wrote could be adjusted to include all occurrences within the source cells instead of just the one per cell, the code would solve the problem and be perfect.
 
Upvote 0

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December
If the code you wrote could be adjusted to include all occurrences within the source cells instead of just the one per cell, the code would solve the problem and be perfect.
Just reminding you of what I said originally...

"It has been my experience that "keeping it simple" usually means
the poster will be back for an expanded solution when the solution
to the simple problem fails to work correctly on the actual data."

If you had simply posted a representative sample of your data like I asked for, I would not have had to go back and rework my code. Just saying...

Okay, my previous code placed the results next to the cell containing the required date, but with multiple dates per cell, I decided to simply list the found dates and associated text one under the other down Columns D and E like you appear to have suggested in Message #9...
Code:
ub GetTextCommaSpaceDate()
  Dim R As Long, X As Long, Z As Long, Data As Variant, Result As Variant
  Const CharsPriorToCommaSpace As Long = 12
  Data = Range("A1", Cells(Rows.Count, "A").End(xlUp))
  ReDim Result(1 To 2 * UBound(Data), 1 To 2)
  For R = 1 To UBound(Data)
    If Data(R, 1) Like "*, ##/##/##*" Then
      For X = 1 To Len(Data(R, 1))
        If Mid(Data(R, 1), X, 10) Like ", ##/##/##" Then
          Z = Z + 1
          Result(Z, 1) = Right(Left(Data(R, 1), X - 1), CharsPriorToCommaSpace)
          Result(Z, 2) = CDate(Mid(Data(R, 1), X + 2, 8))
        End If
      Next
    End If
  Next
  Range("B1").Resize(UBound(Result), 2) = Result
End Sub
 
Upvote 0
Rick, Sorry about what you said. It was the only way I could think to explain the situation the best way I know how.

With the last code you posted above, I am getting run time error 9 subscript out of range
 
Upvote 0
With the last code you posted above, I am getting run time error 9 subscript out of range
The code worked for me in my testing...

What line of code did that error occur on?

What text was in the cell it was processing at the time?
 
Upvote 0
The line shown in yellow was: Result(Z, 1) = Right(Left(Data(R, 1), X - 1), CharsPriorToCommaSpace)


25 cells of information were tested in column A each containing a paragraph of information within such as the sample below:

Orthopedic Consultation, 08/21/08. Pages 2, etc. are missing. 57-year-old with chief complaint of low back pain radiating to the left leg and bilateral foot numbness. Onset of pain was in 2007. No specific injury, possibly due to heavy lifting at work. Pain has been progressive. Radicular component upon coughing or sneezing. Numbness on soles of both feet. Medications: Metformin; Atenolol; Zoloft and vitamins. Orthopedic Consultation, 04/28/11. Left leg and low back pain for three years. Numbness and tingling in her foot. She does a great deal of lifting at work. Past medical history: Hypertension and diabetes. Medications: Atenolol 50 mg qd; Metformin and Zoloft. Family history: Diabetes, hypertension, brain tumor, Alzheimer’s. The applicant does not smoke or use alcohol. She is alert, cooperative and oriented. The applicant’s gait is normal. She has no deformities of the spine, excessive lumbar lordosis or scoliosis clinically. Reflexes are symmetrically depressed. Impression: Sciatica probably related to a disc, rule out HNP at L4-L5 on the left. Recommendation: Lumbar spine MRI. Information Form, 04/28/11. Medications: Atenolol 50 mg; Metformin ER 500 mg; Zoloft 25 mg. Constant left leg, low back buttock pain. Psychiatric: Negative for memory loss or confusion, nervousness, depression. Positive for insomnia.
 
Upvote 0
In order to keep the code fast, I do everything in memory and output the answer at the end of the process. In order to do, I had to guess at how many possible values would be outputted at maximum. Based on your previous posts, assumed the text would be small and that it would contain maybe one or two comma/space/dates text strings on average. Now that I see your actual data, I see my guess was off. Again, to press a point, posting representative sample data, as I requested, would have allowed me to make a better guess. Also, to press a point, I did say in Message #4...

"It has been my experience that "keeping it simple" usually means
the poster will be back for an expanded solution when the solution
to the simple problem fails to work correctly on the actual data."

You said that would not happen... but look... it did. Next time one of the people you ask to help you asks you a question or requests additional information, please just answer the request instead of spending more time telling us why you won't than would have taken to simply provide what was asked for... based on our experience answering forum questions, we actually do have a reason for asking whatever it is we ask. And besides, you ended up posting it anyway, so you might as well simply posted it initially and save the time that was lost (not to mention my time in having to rework the code).

Okay, admonishment period is over... see if this modified code works for you. If you still get an error, increase the size of the number I highlighted in red but don't go overboard in changing the number though, as the larger the number, the less rows of data you will be able to process (using 5 will allow for 200,000 total rows of data, change it to 10 and the maximum number of rows drops to 100,000)...
Code:
Sub GetTextCommaSpaceDate()
  Dim R As Long, X As Long, Z As Long, Data As Variant, Result As Variant
  Const CharsPriorToCommaSpace As Long = 12
  Data = Range("A1", Cells(Rows.Count, "A").End(xlUp))
  ReDim Result(1 To [B][COLOR="#FF0000"][SIZE=2]5[/SIZE][/COLOR][/B] * UBound(Data), 1 To 2)
  For R = 1 To UBound(Data)
    If Data(R, 1) Like "*, ##/##/##*" Then
      For X = 1 To Len(Data(R, 1))
        If Mid(Data(R, 1), X, 10) Like ", ##/##/##" Then
          Z = Z + 1
          Result(Z, 1) = Right(Left(Data(R, 1), X - 1), CharsPriorToCommaSpace)
          Result(Z, 2) = CDate(Mid(Data(R, 1), X + 2, 8))
        End If
      Next
    End If
  Next
  Range("B1").Resize(UBound(Result), 2) = Result
End Sub
 
Last edited:
Upvote 0
That one did the job just perfectly. Thanks so very much to you and everyone here on Mr. Excel that have been such a great help over the past year. I am sorry I have caused any problem. The points about me above are well taken and I certainly won't let that happen again. I am very sorry.

I have always tried to end my posts on a good positive note and will do so by ending as follows: My total respect and admiration for the efforts again on this one. Thank you
 
Upvote 0
Sorry, I'm returning to the 'admonishment' for a moment, hopefully to help clarify for the future. I will then offer other suggestions here. :)

Those previous examples you gave have no relevancy to this situation. This one would stand on it's own as a function without the affect of the previous solutions you referred to.
I think you may have missed my point. My points at the start of post #6 were supporting Rick's assertion that posters who give a brief description without representative data, usually have to come back for a modified solution when the given solution fails on their real data.

My point 1. was simply using yourself as a good example, where in that other thread I quoted from you made a statement of what was required, got some solutions that did exactly that, then returned to say that your requirement actually wasn't what you had first stated. If we had seen a set of representative data in that thread we may have asked the question about repeated characters before spending time developing a solution.


The examples I gave above in post 3 are as pinpointed as can be I think.
Are they? You never addressed my point 2. in post #6. The dates in post #3 contain "-" whereas post #1 used "/". The fact that Rick's code apparently does what you want makes me think you don't have any dates like "04-24-13", but representative data might have confirmed that one way or the other.


I would think in my limited understanding that if the code could search and find ANY occurrence, anywhere in the source of "comma-spacebar-date, then deliver the previous 10 characters prior to the comma, regardless of what they are, into cell in B and the date in C, that would do it.
One of the problems we often encounter is the OP deciding how they would attack the problem & give information based only on that rather than giving helpers what they want to know because they might have several different possible methods and would choose the most appropriate one based on the actual structure and variety of the data.

Anyway, I'm offering two further options.
The first is somewhat similar to Rick's but should be faster (not really relevant if your data is not very big & I don't think you have mentioned how much data there might be) as it 'skips' through the text in bigger chunks. It also uses the guess of a maximum of 5 relevant dates in each cell. It is different to Rick's in that it would also pick up any dates in "mm-dd-yy" format or say like "1 Mar 15". I don't know if you would want that or not or perhaps it just isn't relevant.

Rich (BB code):
Sub GetTCSD1()
  Dim Data As Variant, Result As Variant, d As Variant
  Dim r As Long, z As Long, pos As Long
  Dim s As String
  
  Const TextLen As Long = 12

  Data = Range("A1", Cells(Rows.Count, "A").End(xlUp)).Value
  ReDim Result(1 To 5 * UBound(Data), 1 To 2)
  For r = 1 To UBound(Data)
    s = Data(r, 1)
    Do
      pos = InStr(pos + 1, s, ", ")
      If pos > 0 Then
        d = Mid(s, pos + 2, 8)
        If IsDate(d) Then
          z = z + 1
          Result(z, 1) = Right(Left(s, pos - 1), TextLen)
          Result(z, 2) = d
        End If
      End If
    Loop Until pos = 0
  Next r
  Range("B1").Resize(z, 2) = Result
End Sub

The following is similar but allows for any number of relevant dates in a cell, however it is marginally slower than the code above.

Rich (BB code):
Sub GetTCSD2()
  Dim Data As Variant, Result As Variant, d As Variant
  Dim r As Long, z As Long, pos As Long
  Dim s As String
  
  Const TextLen As Long = 12
 
  Data = Range("A1", Cells(Rows.Count, "A").End(xlUp)).Value
  ReDim Result(1 To 2, 1 To 1)
  For r = 1 To UBound(Data)
    s = Data(r, 1)
    Do
      pos = InStr(pos + 1, s, ", ")
      If pos > 0 Then
        d = Mid(s, pos + 2, 8)
        If IsDate(d) Then
          z = z + 1
          ReDim Preserve Result(1 To 2, 1 To z)
          Result(1, z) = Right(Left(s, pos - 1), TextLen)
          Result(2, z) = d
        End If
      End If
    Loop Until pos = 0
  Next r
  Range("B1").Resize(z, 2) = Application.Transpose(Result)
End Sub
 
Upvote 0
Peter, I am very thankful for both the two code versions as well as the great advice. Both codes work excellent. One point of great importance was what you said about the second code having the ability to deal with more data as it should become necessary soon. Thanks for being a step ahead on that one.


Regarding the "admonishment" area, you have no idea how thankful I am that you brought this to my attention as did Rick. Sometimes we just can't see what we're actually doing and others can. A perfect example of this was what you explained about bringing in example situations from other threads I had posted previously. You are absolutely 100% correct. I completely totally 100% misunderstood what the point was and for the life of me can't figure out how that one went right over my head. I actually thought you are using those past threads as a reference to constructing the current one, which is why I answered there is no relevancy in an effort to try to be helpful. If I look back at my answer to you on that one in comparison with the intent of your actual question, it actually appears tremendously insulting and I can see it now and I am so very very sorry. Once again, my fault through my misinterpretation. I am also shocked that somehow the date question also got by me. I see now clearly that simply stating that I had already covered in above was quite deficient. What I needed to have said was the proper format is in the original example on the original post or something to that nature. Again my oversight, my apologies.


Your point well made about the OP deciding how they will attack the problem was especially significant to me. This incident was truly a perfect example. In retrospect, it almost appears like I am a patient going to a doctor and telling the Dr. how to diagnose me when I absolutely have no idea what I'm talking about myself. Again, I now see very clearly what you both were talking about and will make sure I don't make that mistake again because everyone's kind and generous contributions are most valuable.

I was also very thankful and appreciative for the very fact that after I even thought the thread was over, you still followed up as a final note to The thread with the great contribution and advise. My sincere compliments for the great moderation.


In conclusion, feel free to use me as an example to others by pointing them to this thread to illustrate the value of the very advice you both have shared with me and could possibly be of value to others as well who may benefit from a visual illustration supporting the points you are making to someone else like myself. Thanks one more time to all those who have been so helpful there at Mr. Excel most especially and including yourself and Rick.
 
Upvote 0
skyport

Thanks for your message. If you post more questions in the future, I'm sure we will have better information & if Rick or I think we can contribute, we will. :)

I liked the following comparison, as I have been guilty of exactly that recently (doesn't Google know everything) & been put firmly back in my place by my doctor! :eek:
In retrospect, it almost appears like I am a patient going to a doctor and telling the Dr. how to diagnose me when I absolutely have no idea what I'm talking about myself.
 
Upvote 0

Forum statistics

Threads
1,216,438
Messages
6,130,632
Members
449,584
Latest member
c_clark

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top