从VBA中的用户输入范围循环遍历每一行

时间:2017-05-18 10:57:35

标签: excel-vba vba excel

我已经研究了很长一段时间,但到目前为止我的代码都没有,所以我希望有人可以提供帮助。我创建了一个userform,它有2个输入框和一个命令按钮。我希望命令按钮一次突出显示每一行,然后打印出每个高亮行的副本。例如,用户输入“A5:J5”作为textbox1的起始行,然后输入“A30:J30”作为textbox2的结束行。我希望命令按钮一次自动突出显示一行,并为每行打印1份。 这是代码的一部分。没有更新循环和偏移(这无论如何都不起作用),因为我目前没有更新的代码副本。我将不胜感激任何帮助。谢谢。

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

1 个答案:

答案 0 :(得分:0)

尝试以下内容。似乎对我有用。

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