|
-
February 23rd, 2009, 03:47 PM
#1
Easy String Delete / Insert
****************** Dedicated To WoF! *********************
String editing in VB is a drag! It involves a mixture of Left, Mid, Right, and Len functions. Errors will creep in if calculations of position result in negative values.
Here I go again!
My little di (short for Deletion & Insertion) will change all that!
You just supply:
* Txt$ (string to process)
* N (number of characters to delete)
* Position (where change will take place)
* Insert (characters to insert)
And di will take care of the details!
If Position is positive, change will take place there (or after the end of Txt$).
If Position is negative, it will be calculated backwards from the end of the string. If the result is less than 1, Position = 1
If Position is omitted altogether, action will take place at the end of Txt$. In such case, Position may be used to pass Insertion (in order to avoid the ugly empty comma!)
Please use this little sub and suggest improvements!
' these lines are for testing purposes
Private Sub Form_Load()
Dim txt$
txt$ = "abcdef": Call di(txt$, 1, 2): MsgBox (txt$)
txt$ = "abcdef": Call di(txt$, 1, 2, "X"): MsgBox (txt$)
txt$ = "abcdef": Call di(txt$, 1, -2, "X"): MsgBox (txt$)
txt$ = "abcdef": Call di(txt$, 1, "X"): MsgBox (txt$)
txt$ = "abcdef": Call di(txt$, 1, , "X"): MsgBox (txt$)
txt$ = "abcdef": Call di(txt$, 1, 100, "X"): MsgBox (txt$)
txt$ = "abcdef": Call di(txt$, 100, 1, "X"): MsgBox (txt$)
End Sub
' String Delete and/or Insert
' ~~~~~~~~~~~~~~~~~~~~~~~~~
Sub di(Txt As String, Optional N As Integer = 0, Optional Position As Variant = "", Optional insert As String = "")
' Calc Position
If IsNumeric(Position) = True Then
If Position = 0 Then Position = (Len(Txt) + 1) - Abs(N)
If Position < 0 Then Position = (Len(Txt) + 1) - Abs(Position)
Else
If Position = Nul$ Then
Position = (Len(Txt) + 1) - Abs(N)
Else
If insert = Nul$ Then insert = Position
Position = (Len(Txt) + 1) - Abs(N)
End If
End If
' Do it
Txt = Left$(Txt, Position - 1) + insert + Mid$(Txt, Position + N)
End Sub
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|