VBs String function is useful to fill a large string with a specific character. Occasionally, you might need to fill a string with a repeating set of characters. If youre using a small database held inside a string, for example, you might want to set default values for some of the fields.
When the need does arise, you can use VBs Mid statement to handle the task:
Dim Data As String
Const Rep = "ABCD"
Data = Rep & Space$(1000)
Mid$(Data, Len(Rep) + 1) = Data
These last two statements do a significant amount of work. The first line allocates the required memory, and the second fills that memory with character datathats pretty good for only two lines of code. Not surprisingly, this step is quick, even for large strings, and it provides better functionality than VBs regular String function:
Public Function Replicate (ByVal Number As Long, _
ByVal Pattern As String) As String
' Returns PATTERN replicated in a string NUMBER times.
' Number = Number of replications desired
' Pattern = Character pattern to replicate
Dim LP As Long
Dim sRet As String
If Number > 0 Then
LP = Len(Pattern)
If LP > 1 Then
sRet = Pattern & Space$((Number - 1) * LP)
If Number > 1 Then
Mid$(sRet, LP + 1) = sRet
End If
Else
sRet = String$(Number, Pattern)
End If
End If
Replicate = sRet
End Function
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible.
Submit your tip here.