如何遍历列表并打印输出

时间:2020-06-29 02:57:41

标签: excel vba macos

我真的是Excel VBA的新手,但最近需要提出一种解决方案,以使excel遍历列表并打印输出。

在选项卡“ Sheet2”上,这里是项目主数据。每个项目都指定了一个项目代码。

sheet2

在“ Sheet1”上,我有一个公式可以找到单价和起始价,并计算现有总负债。

Sheet1

我想让Excel在工作表Sheet1!A2中填充工作表Sheet2!A1:A中的每个值,进行计算,并将所有输出粘贴到新工作表中,如下所示。 / p>

enter image description here

谢谢。

2 个答案:

答案 0 :(得分:1)

我做了一个基本的宏来做到这一点,也许您可​​以对其进行调整以满足您的需求。

Option Explicit

Sub Test()

    Dim rng As Range
    Dim switch As Boolean
    
    switch = False
    
    For Each rng In Worksheets("Sheet2").Range("A2", Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp))
        Worksheets("Sheet1").Select
        Range("A" & Rows.Count).End(xlUp).Select
        
'so that for the first iteration it will not offset, assuming you start off with blank wksht
        If switch = True Then
            ActiveCell.Offset(2, 0).Select
        End If

        ActiveCell.Value = "Item Number"
        ActiveCell.Offset(0, 1).Value = "Description"
        ActiveCell.Offset(0, 2).Value = "On Hand Liability"
        ActiveCell.Offset(1, 0).Value = rng.Value
        ActiveCell.Offset(1, 1).Value = rng.Offset(0, 1).Value
        ActiveCell.Offset(1, 2).Value = rng.Offset(0, 2) * rng.Offset(0, 3)
        switch = True
    Next rng


End Sub

答案 1 :(得分:1)

建议您使用Microsoft VBA语言参考来查找循环。例如。 https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/for-eachnext-statement

这是一个将产生输出的示例:

Option Explicit

Public Sub PopulateSheet1()

    Dim SourceSheet As Worksheet
    Dim SourceRow As Range
    Dim SourceRows  As Long
    Dim TargetSheet As Worksheet
    Dim TargetRow As Long
    
    Set SourceSheet = ActiveWorkbook.Sheets("Sheet2")
    Set TargetSheet = ActiveWorkbook.Sheets("Sheet1")
    
    SourceRows = SourceSheet.Cells(Rows.Count, 1).End(xlUp).Row
    TargetRow = 1
    For Each SourceRow In SourceSheet.Range("A2:A" & SourceRows)
        TargetSheet.Cells(TargetRow, 1) = Array("Item Number", "Description", "On Hand Liability")
        TargetRow = TargetRow + 1
        
        SourceRow.Cells(1, 1).Copy TargetSheet.Cells(TargetRow, 1)
        TargetSheet.Cells(TargetRow, 2) = "=VLOOKUP(Sheet1!A" & TargetRow & ",Sheet2!A:B,2,FALSE)"
        TargetSheet.Cells(TargetRow, 3) = "=VLOOKUP(Sheet1!A" & TargetRow & ",Sheet2!A:D,3,FALSE) * VLOOKUP(Sheet1!A" & TargetRow & ",Sheet2!A:D,4,FALSE)"
        TargetSheet.Cells(TargetRow, 3).NumberFormat = "$#,##0.00"
        TargetRow = TargetRow + 2
    Next

End Sub