Hi, I want to increase some string by 1 in VBA. For example, I have 00sad231f and I want to get 00sad231g. In other languages than VB, you can simply write "00sad231f"+1. Do I have any other options than write comlicated code? Thank you.
Hi, I want to increase some string by 1 in VBA. For example, I have 00sad231f and I want to get 00sad231g. In other languages than VB, you can simply write "00sad231f"+1. Do I have any other options than write comlicated code? Thank you.
Very simply with no bound checking etc.Originally Posted by mik
sVal = "00sad231f" sVal = Left(sVal, Len(sVal) - 1) & Chr(Asc(Right(sVal, 1)) + 1) Debug.Print sVal
It works! Thank you! Bound checking would be nice (only A-Z 0-9 are allowed), but this helps anyway.
Originally Posted by mik
Function ChangeLast(val As String) Dim sTemp As String sTemp = Chr(Asc(Right(val, 1))) Select Case Asc(sTemp) Case 48 To 56, 65 To 89, 97 To 121: sTemp = Chr(Asc(sTemp) + 1) Case Else: 'do nothing End Select ChangeLast = Left(val, Len(val) - 1) & sTemp End Function
Thank you once again. The code doesn't work-for strings, that end with z or 9, it returns the same string..
my point is to get from the string 403fjorz 403fjos1, from 403fjor9 403fjora etc.. I know this is quite complicated and has to be made by some cycle..
You want my blood tooOriginally Posted by mik
Function ChangeLast(val As String) Dim sTemp As String sTemp = Chr(Asc(Right(val, 1))) Select Case Asc(sTemp) Case 48 To 56, 65 To 89, 97 To 121: sTemp = Chr(Asc(sTemp) + 1) Case 57: sTemp = Chr(65) Case 90: sTemp = Chr(97) Case 122: sTemp = Chr(48) Case Else: 'do nothing End Select ChangeLast = Left(val, Len(val) - 1) & sTemp End Function
Thank goodness for that - it's not just me who gives you a hard time...Originally Posted by xld
Still not exactly what I meant-it changes only last char.. Nevermind, I managed to code it myself, but xld> You helped me a lot!! Thank you very much for your effort, time and quickness of your answers.
here is the code, if anyone is interested:
Function increaseStr2(s) Dim varData(20) As Variant 'varData = s Max = Len(s) For n = 0 To (Max - 1) varData(Max - n) = Mid(s, Max - n, 1) Next ' ve vardata mame pole For n = 0 To (Max - 1) v2 = varData(Max - n) lastChDec = Asc(Right(v2, 1)) If (lastChDec < 57) Then lastChDec = lastChDec + 1 GoTo EOC End If If (lastChDec > 96 And lastChDec < 122) Then lastChDec = lastChDec + 1 GoTo EOC End If If (lastChDec = 122) Then lastChDec = 48 varData(Max - n) = Chr(lastChDec) End If If (lastChDec = 57) Then lastChDec = 97 GoTo EOC End If Next EOC: varData(Max - n) = Chr(lastChDec) s = "" For n = 1 To Max s = s & varData(n) Next increaseStr2 = s End Function