Using InStr to select string to copy

tcarter963

New Member
Joined
Aug 3, 2006
Messages
38
I have some text in cell C2 that looks like this: clonidine_Area
I want to copy the text before the underscore and paste it to another cell.

I've gotten this far but don't know how to proceed... How do I use the position number to selectively copy the string that I want? Any help would be greatly appreciated.


Sub Cp()

Dim SearchString, SearchChar, MyPos

SearchString = ActiveSheet.Range("C2")
SearchChar = "_"

MyPos = InStr(1, SearchString, SearchChar, 1)



End Sub
 

Excel Facts

Excel Joke
Why can't spreadsheets drive cars? They crash too often!

Peter_SSs

MrExcel MVP, Moderator
Joined
May 28, 2005
Messages
52,278
Office Version
  1. 365
Platform
  1. Windows
Something like below. Note that it is good practice to 'Dim' your variables as specific data types where possible, rather than leaving them all as Variant type.

<font face=Courier New><br><SPAN style="color:#00007F">Sub</SPAN> Cp()<br>    <SPAN style="color:#00007F">Dim</SPAN> SearchString <SPAN style="color:#00007F">As</SPAN> String, SearchChar <SPAN style="color:#00007F">As</SPAN> String<br>    <SPAN style="color:#00007F">Dim</SPAN> MyPos <SPAN style="color:#00007F">As</SPAN> <SPAN style="color:#00007F">Long</SPAN><br>    <br>    SearchString = ActiveSheet.Range("C2")<br>    SearchChar = "_"<br>    <br>    MyPos = InStr(1, SearchString, SearchChar, 1)<br>    Range("D2").Value = Left(SearchString, MyPos - 1)<br><SPAN style="color:#00007F">End</SPAN> <SPAN style="color:#00007F">Sub</SPAN><br></FONT>
 
Master Excel Bundle

Excel contains over 450 functions, with more added every year. That’s a huge number, so where should you start? Right here with this bundle.

Forum statistics

Threads
1,151,985
Messages
5,767,443
Members
425,414
Latest member
chwein

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
Top