Home > Net >  Set a condition for i = 0 in For Loop
Set a condition for i = 0 in For Loop

Time:08-04

I find myself consistently having to set a condition for i = 0 in my For Loops and am wondering if there's a more efficient way to go about writing the for loop. For example:

For i = 0 to UBound(arr)
    If i = 0 then
        ws.range("A1") = arr(i)
        else
            ws.range("A1") = ws.range("A1") & ", " & arr(i)
    End If
Next i

Basically I'm wondering if this is the most efficient way to do this or if there's something I'm missing that would make this much more efficient.

CodePudding user response:

Join() is probably your best bet here, but you can simplify the type of loop you posted so there's only one cell write:

Dim i As Long, sep As String, v As String

For i = 0 To UBound(arr)
    v = v & sep & arr(i)
    sep = ", " 'assign after first value
Next i
ws.Range("A1").Value = v

CodePudding user response:

If you want to do it with a loop you could also do it like that

Dim s As String
For i = 0 To UBound(arr)
        s = s & arr(i) & ","
Next i
ws.Range("A1").Value = Left(s, Len(s) - 1)
  • Related