Sunday, September 1, 2019

Finding a String within a List of Strings

Don't you think it's too easy to perform such a procedure using INSTR function?
Yup, it's damn easy but the reason behind writing this post was a little bit core side of the problem.
Let's take an example here

suppose you have 100 cells containing a string. Now, you want to extract the cell address where the cell's string contains "1p" or anything else.
Now, Cell's string could have been anything but you have to find a specific string within a set of cells.
It's very easy to find such using following code.

dim I as Long 
For I = 1 to 100 Step 1
if VBA.Instr(1,Cells(I,1).value, "1p") > 0 then 
msgbox .cells(i,1).Address
end if 
Next I 

Above code will simply give you the address of the matching cell with string. But here comes the catch. String 1p is in standard or lower case and you might don't know in the cells which case would be there so, to avoid that confusion programmer generally uses the following line using OR logical treatment.

dim I as Long 
For I = 1 to 100 Step 1
if VBA.Instr(1,Cells(I,1).value, "1p") > 0 or VBA.Instr(1,Cells(I,1).value, "1P") then 
msgbox .cells(i,1).Address
end if 
Next I

But believe me, to execute the proper way is a bit easy and different using inbuild VBA functions. Because more stuff on the logical operation the processor would take more time to process it. So better is to use the following idea to process the same thing using  UCASE function.

dim I as Long 
For I = 1 to 100 Step 1
if VBA.Instr(1,UCASE(Cells(I,1).value), UCASE("1p")) > 0  then 
msgbox .cells(i,1).Address
end if 
Next I

Function UCASE will consider each alphabet in the string as UPPER case and that's how you bypass the CASE issue while finding them and matching the string withing string.

Our group member Anil Khanna Karunakaran has asked my this query at personal so I thought this could be a learning point for many friends.
See these kinds of little techniques are a very important part of programmers. Actually, this small difference actually defines the programmers sometimes in some situations.

Moral of the story is everything is capable to provide results. but the good programmers will do it more creative way. So, kindly share your techniques here with us to solve some general issues.

- Kamal Bharakhda

No comments:

Post a Comment

IsValidPasswordString Function

'Following function will verify if the password string contains following characters or not? Rem : List of Characters Group - ASCII Rem ...