Home » excel » excel – How to write on multiple rows/cells

excel – How to write on multiple rows/cells

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to write a looping macro to write text on multiple sequential lines (say 1000) from my active cell. I have pasted what I have already tried below… I think I might be close, but I’m clearly missing some important details. Can someone help?

Sub firstloop()
    Dim Total As Long
    Dim Count As Long
    Total = 0
    For Count = 1 To 1000
        Count = Total + Count
    ActiveCell = "Test"
    ActiveCell.Offset(1, 0) = ActiveCell
    Next Count
End Sub
How to&Answers:

Get rid of the two ActiveCell and use:

Sub firstloop()

    Dim rng as range
    Set rng = selection

    Dim Count As Long
    For Count = 1 To 1000
        rng.offset(count - 1,0).Value = "Test"
    Next Count
End Sub

Answer:

Values 1000

Cells(1) is used to avoid unexpected result if a range with more than 1 cell is selected.

ActiveCell Excluded

Sub Values1000()

    Const strText As String = "Text"
    Const cNumber As Long = 1000

    Selection.Cells(1).Offset(1).Resize(cNumber) = strText

End Sub

ActiveCell Included

Sub Values1000()

    Const strText As String = "Text"
    Const cNumber As Long = 1000

    Selection.Cells(1).Resize(cNumber) = strText

End Sub

Or just replace the constants with their values and you have a one-line code.

Answer:

Sub firstloop()

    Dim Count As Long
    Dim rng As Range
    Set rng = ActiveCell

    For Count = 1 To 1000
        rng.Offset(Count - 1, 0) = "Test"
    Next Count
End Sub