View Single Post
  #8   Report Post  
Posted to microsoft.public.excel.programming
Rick Rothstein \(MVP - VB\) Rick Rothstein \(MVP - VB\) is offline
external usenet poster
 
Posts: 2,202
Default Incrementing a string

Column C contains string IDs with a varying number of blank cells between
each.

Having found the last entry in column E and the latest ID with:

iDoorRow = Sheets("Pages").Cells(Rows.Count, 5).End(xlUp).Row

sDoorName = Sheets("Pages").Cells(iDoorRow, 5)

how can I increment the string (sDoorName) (in this case D02-003) to
D02-004?
Then I can prompt the user to confirm that as the next door or to type in
D03-001 to start the next sequence or whatever.


You can use this function to return the next number in the sequence (if it
is 000

Function NextName(sDoorname As String) As String
NextName = sDoorname
Mid(NextName, 5) = Format((Val(Mid(NextName, 5)) + 1) Mod 1000, "000")
End Function

Or, if you are not repeating the process several times, embed the two
lines from the function directly in your code (making sure you Dim the
NextName variable in that case).


One other comment on the function I posted... I assumed you would be
checking to see if the maximum number of "doornames" had been assigned
**after** you tried to increment it. However, that is not necessary and it
occurred to me that you are probably already checking for that condition
before trying to increment the "doorname". If that is the case, then the Mod
operation can be removed from my code, making it noticeably shorter....

Function NextName(sDoorname As String) As String
NextName = sDoorname
Mid(NextName, 5) = Format(Val(Mid(NextName, 5)) + 1, "000")
End Function

And, although I prefer coercing data types manually (hence, the Val function
call), you could let VB do it for you relatively safely in this particular
case...

Function NextName(sDoorname As String) As String
NextName = sDoorname
Mid(NextName, 5) = Format(Mid(NextName, 5) + 1, "000")
End Function

thus shortening the code even more.

Rick