Need excel formula to insert underscore before the Proper case letter where ever find it in a string.

ManiThani

New Member
Joined
Jan 20, 2017
Messages
9
I need to replace a string like below:

IpArId to be converted as Ip_Ar_Id

Wherever the upper cases identified in a string to be prefixed with "underscore" ("_").
 

Excel Facts

Convert text numbers to real numbers
Select a column containing text numbers. Press Alt+D E F to quickly convert text to numbers. Faster than "Convert to Number"
IpArId to be converted as Ip_Ar_Id

Wherever the upper cases identified in a string to be prefixed with "underscore" ("_").
Except if it is the first character in the string?

You could try this user-defined function. To implement ..
1. Right click the sheet name tab and choose "View Code".
2. In the Visual Basic window use the menu to Insert|Module
3. Copy and Paste the code below into the main right hand pane that opens at step 2.
4. Close the Visual Basic window.
5. Enter the formula as shown in the screen shot below and copy down.
6. Your workbook will need to be saved as a macro-enabled workbook (*.xlsm)

Code:
Function Underscore(s As String) As String
  Static RX As Object
  
  If RX Is Nothing Then
    Set RX = CreateObject("VBScript.RegExp")
    RX.Global = True
  End If
  RX.Pattern = "([A-Z])"
  Underscore = s
  If RX.Test(s) Then Underscore = Left(s, 1) & RX.Replace(Mid(s, 2), "_$1")
End Function

Excel Workbook
AB
1IpArIdIp_Ar_Id
2
3catcat
4AbcdEFGHAbcd_E_F_G_H
5dOgd_Og
Sheet2
 
Last edited:
Upvote 0
An alternative would be ..
Code:
Function Under_Score(s As String) As String
  Dim i As Long
  
  For i = Len(s) To 2 Step -1
    If Mid(s, i, 1) Like "[A-Z]" Then s = Left(s, i - 1) & "_" & Mid(s, i)
  Next i
  Under_Score = s
End Function
 
Upvote 0

Forum statistics

Threads
1,224,818
Messages
6,181,152
Members
453,021
Latest member
Justyna P

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