Ivan Gerasimenko
Ivan Gerasimenko

Reputation: 2428

Is there any build-in function in VBScript to repeat a string N-times?

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"

Upvotes: 12

Views: 17311

Answers (6)

Przemo Szew
Przemo Szew

Reputation: 1

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

Upvotes: 0

hideo
hideo

Reputation: 47

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".

Upvotes: -1

Gio
Gio

Reputation: 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! :)

Upvotes: -1

Excel Hero
Excel Hero

Reputation: 14764

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

Upvotes: 4

MC ND
MC ND

Reputation: 70933

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

Upvotes: 3

Alex K.
Alex K.

Reputation: 175826

No, nothing built in. Instead:

n      = 5
str    = "Ab"
result = replace(space(n), " ", str)

Upvotes: 47

Related Questions