0

第二个问题大家好,这是我的第二个问题;

我正在尝试通过循环编写一个 vba 代码,它可以在工作表http://speedy.sh/pvVEX/stack1.xlsx中执行以下操作

1) 检查表 BE 有多少个苹果Aasif并将其插入Sheet1,行Aasif和列在哪里Apples,然后检查有多少个orangesAasif插入行Aasif和列在哪里Oranges

2)检查所有水果后,它应该来到下一个人,Aeleta然后每列再次相同

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

4

1 回答 1

1

这并不难;)请看一个好的起点

我正在为您提供与您在链接中提供的电子表格一起使用的代码。它将"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

结束子

结果 结果

于 2013-07-22T12:16:10.487 回答