在循环遍历电子表格中的行时定位特定值

时间:2013-07-22 11:05:02

标签: loops excel-vba reference copy copy-paste

第二个问题 大家好, 在这里,我使用我的第二个查询;

我正在尝试通过循环编写vba代码,这可以在工作表http://speedy.sh/pvVEX/stack1.xlsx

中执行以下操作

1)检查表单BE Aasif有多少苹果并将其插入Sheet1,其中行为Aasif且列为Apples,然后检查有多少oranges AasifAasif并插入行Oranges且列为Aeleta

2)检查完所有水果后,它应该转到下一个人{{1}},然后每个列再次相同

我是vba循环新手,虽然我已经做了一些其他查询,所以非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

这并不难;) 请参阅a good starting point

我正在为您提供与您在链接中提供的电子表格一起使用的代码。它将根据"Sheet1"中的列表填充"Sheet2" 注意: 确保您的工作表名为Sheet1和Sheet2,或相应地修改代码

Sub Main()

Dim ws1 As Worksheet, ws2 As Worksheet ' sheet variables declaration
Set ws1 = Sheets("Sheet1"): Set ws2 = Sheets("Sheet2") ' binding sheets to variables

Dim rng1 As Range, rng2 As Range ' range variables
Dim i As Long, j As Long, k As Long ' iterators

' for each cell in column F in sheet2
For i = 2 To ws2.Range("F" & Rows.Count).End(xlUp).Row
    Set rng2 = ws2.Range("F" & i) ' binding cells from column F (sheet2) to rng2 variable
    ' for each cell in column B on sheet1
    For j = 2 To ws1.Range("B" & Rows.Count).End(xlUp).Row
        Set rng1 = ws1.Range("B" & j) ' binding cells from column B (sheet1) to rng1 variable
        ' comparing both words ( names )
        If StrComp(rng2, rng1, 1) = 0 Then
            For Each Column In Sheet1
            For k = 3 To ws1.Cells(1, Columns.Count).End(xlToLeft).Column
                ' if the name of column matches the offset or rng2 (name)
                If StrComp(rng2.Offset(0, 1), Cells(1, k), 1) = 0 Then
                    ' copy/paste the amount of fruits from sheet2 to corresponding cells in sheet1
                    Cells(rng1.Row, k) = rng2.Offset(0, 2)
                End If
            Next k ' next column
        End If
        Set rng1 = Nothing
    Next j ' next row in sheet1
    Set rng2 = Nothing
Next i ' next row in sheet2

End Sub

结果 Results