9

There is a function in VBScript String(number,character) returns a string that contains a repeating character of a specified length. E.g.:

String(5, "A")     ' output: "AAAAA"

Is there any function to repeat a string? E.g.:

RepeatString(5, "Ab")     ' output "AbAbAbAbAb"
Ivan Gerasimenko
  • 2,381
  • 3
  • 30
  • 46

6 Answers6

41

No, nothing built in. Instead:

n      = 5
str    = "Ab"
result = replace(space(n), " ", str)
Alex K.
  • 171,639
  • 30
  • 264
  • 288
3

For code brevity, the accepted answer is good. But the following function is literally 10 times as fast. And it's twice as fast as RepeatString(). It uses a little-known feature of Mid where it fills the remainder of a string buffer with a repeating pattern in one go...

Function Repeat$(ByVal n&, s$)
    Dim r&
    r = Len(s)
    If n < 1 Then Exit Function
    If r = 0 Then Exit Function
    If r = 1 Then Repeat = String$(n, s): Exit Function
    Repeat = Space$(n * r)
    Mid$(Repeat, 1) = s: If n > 1 Then Mid$(Repeat, r + 1) = Repeat
End Function
Excel Hero
  • 14,253
  • 4
  • 33
  • 40
2

For a general simple solution

Function RepeatString( number, text )
    Redim buffer(number)
    RepeatString = Join( buffer, text )
End Function

But if the text is short but the number of repetitions is high, this is a much faster solution

Function RepeatString( ByVal number, ByVal text )
    RepeatString=""
    While (number > 0)
        If number And 1 Then 
            RepeatString = RepeatString & text
        End If 
        number = number \ 2 
        If number > 0 Then
            text = text & text 
        End If 
    Wend
End Function
MC ND
  • 69,615
  • 8
  • 84
  • 126
0

Here's another way to accomplish this using built-in excel formula REPT()

Function RepeatMyStringTimes()
    Const myString As String = "Some String"
    Const Times As Byte = 7
    Debug.Print Excel.WorksheetFunction.Rept("S", Times)
End Function
-1

FYI I needed to have a 10-character string repeated more then 25 million times and the function Repeat$(ByVal n&, s$) took half a second to perform it, it saved my day! :)

Gio
  • 1
  • 1
-1

We can create a simple custom function like this

Function RepeatString(Byval AString As String, byval Times As Long)
    If AString = vbNullString Or Times < 0 Then RepeatString = CVErr(xlErrNA): Exit Function
    Dim i As Long
    Dim result As String
    For i = 1 To Times
        result = result & AString
    Next
    RepeatString = result
End Function

Or use String function to return repeating character strings of the length specified.

Dim MyString
MyString = String(5, "*")    ' Returns "*****".
MyString = String(5, 42)    ' Returns "*****".
MyString = String(10, "ABC")    ' Returns "AAAAAAAAAA".
hideo
  • 37
  • 4