VBA从for循环返回下一个值

时间:2017-09-06 18:54:13

标签: excel vba excel-vba

我需要使用For循环中的每个值填充一个单元格。我有一个包含员工姓名和员工ID的工作表。我试图在另一个工作表上填充单元格并打印到默认打印机(或首选PDF),然后对列表中的下一个员工执行相同操作。

非常感谢任何帮助。我目前只返回第一个员工姓名而没有ID。

Sub btn_CompleteForm()

Dim Rng As Range, cell As Range, EmpName As Range
Set NameRng = Range("Employees!A2:Employees!A10")
Set IDRng = Range("Employees!B2:Employees!B10")
Set EmpName = Range("ActionNotice!D7")
Set EmpID = Range("ActionNotice!D8")

For Each cell In NameRng
    EmpName = NameRng.Value
    EmpID = IDRng.Value
    ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
        IgnorePrintAreas:=False
    MsgBox "Next"
Next cell

End Sub

2 个答案:

答案 0 :(得分:2)

   For Each cell In NameRng
        EmpName = NameRng.Value
        EmpID = IDRng.Value
        ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
            IgnorePrintAreas:=False
        MsgBox "Next"
    Next cell

应该是

   For nRow = 1 to NameRng.Count
        EmpName.Value = NameRng.Cells(nRow,1).Value
        EmpID.Value = IDRng.Cells(nRow,1).Value
        ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
            IgnorePrintAreas:=False
        MsgBox "Next"
    Next nRow

答案 1 :(得分:1)

这应该只需要一个简单的修复。将EmpName = NameRng.Value更改为EmpName = cell.Value,将cell循环至NameRng,而不是循环遍历NameRng

Sub btn_CompleteForm()
    Dim Rng As Range, cell As Range, EmpName As Range
    With Worksheets("ActionNotice")
        For Each cell In Range("Employees!A2:Employees!A10")
            .Range("D7") = cell.value                 'Name
            .Range("D8") = cell.Offset(0, 1).value    'ID
            ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
                                                 IgnorePrintAreas:=False
            MsgBox "Next"
        Next cell
    End With
End Sub
相关问题