简体   繁体   English

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

[英]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. 我创建了一个具有2个输入框和一个命令按钮的用户窗体。 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. 例如,用户输入“ A5:J5”作为文本框1的开始行,然后输入“ A30:J30”作为文本框2的结束行。 I want the command button to automatically highlight one row at a time and print out 1 copy for each row. 我希望命令按钮一次自动突出显示一行,并为每一行打印出1份副本。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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