Insert and in Sentence Structure based on string values with commas

mrmmickle1

Well-known Member
Joined
May 11, 2012
Messages
2,461
If I have strings that look like this that I'm trying to fit into a paragraph of text via code:

String 1 = "Methylphenidate, Nordiazepam-Diazepam, Fentanyl"

String 2 = "Methylphenidate, Nordiazepam-Diazepam, Fentanyl, THC"

String 3 = "Methylphenidate, Nordiazepam-Diazepam, Fentanyl, MDMA, THC"

How Can I alter them via VBA code to look like this so they will look proper in a sentence:

String 1 = "Methylphenidate, Nordiazepam-Diazepam and Fentanyl"

String 2 = "Methylphenidate, Nordiazepam-Diazepam, Fentanyl and THC"

String 3 = "Methylphenidate, Nordiazepam-Diazepam, Fentanyl, MDMA and THC"

Any help would be much appreciated.... My brain doesn't seem to be functioning properly today. :)
 

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
I presume from your use of the word "strings" instead of text that this is a VBA question. Give this function a try...
Code:
Function Sentence(S As String) As String
  Dim LastComma As Long
  LastComma = InStrRev(S, ",")
  If InStr(1, Mid(S, LastComma), " and ", vbTextCompare) Then
    Sentence = S
  Else
    Sentence = Application.Replace(S, LastComma, 1, " and")
  End If
End Function
 
Upvote 0
Thanks Rick,

Your function worked like a charm!!

I also used your other tip for adding commas in this Project as well :):

Code:
IDs = IDs & "," & Cell.Value


Range("B2").Value = "'(" & Mid(IDs, 2) & ")"
 
Upvote 0

Forum statistics

Threads
1,214,387
Messages
6,119,222
Members
448,877
Latest member
gb24

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