简体   繁体   中英

Loop through each row from a user input range in VBA

I've been researching on this for quite awhile but none of my code work so far, so I wish someone can help. I created a userform that has 2 input boxes and a command button. I want the command button to highlight each row one at a time and then print out a copy with each higlighted row. For example, the user input "A5:J5" as the starting row from textbox1 then "A30:J30" as the ending row from textbox2. I want the command button to automatically highlight one row at a time and print out 1 copy for each row. Here is a part of the code. Not updated with looping and offset (which doesn't work anyways) as I don't have the copy of my updated code at the moment. I will appreciate any help. Thanks.

Private Sub PrintingButton_Click()

Dim firstrow As String
Dim firstrange As Range

Dim lastrow As String
Dim lastrange As Range

'highlight the firstrow

firstrow = TextBox1.Value
Set firstrange = Range(firstrow)

lastrow = TextBox2.Value
Set lastrange = Range(lastrow)

firstrange.Select
With Selection.Interior
.Color = 65535
'insert printing code here:    ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
    IgnorePrintAreas:=False
End With


End Sub

Try something like the following. Seems to work for me.

Private Sub PrintingButton_Click()
    Dim firstrow As String
    Dim lastrow As String
    Dim rMyRange As Range


    firstrow = TextBox1.Value 'Input value like "A5" (just the upper letf cell of desired range, not range as in you example)
    lastrow = TextBox2.Value 'Input value like "B10" (just the bottom right cell of desired range, not range)

    'data is supposed to be located in sheet "MyData"
    Set rMyRange = Worksheets("MyData").Range(firstrow, lastrow)

        For Each MyRow In rMyRange.Rows
        MyRow.Select
            With Selection.Interior
            .Color = 65535
            'Your printer settings here
            Application.ActivePrinter = "hp photosmart 7200 series (Copiar 1) en Ne01:"
        ActiveWindow.Selection.PrintOut Copies:=1, ActivePrinter:= _
            "hp photosmart 7200 series (Copiar 1) en Ne01:", Collate:=True

            End With
        Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM