IF 和 For 循环中的 VBA For 循环

时间:2021-05-07 22:45:05

标签: excel vba for-loop if-statement

我正在尝试编写一个宏,以将管理员的姓名放入单元格中(如果他们被分配到该类别)。到目前为止我写了这段代码,但它不起作用。我正在尝试获取它,以便如果一个工作表中一列的单元格与另一个工作表的单元格匹配,并且如果匹配,那么它将在单独的单元格中打印管理员的姓名以标识该类别由那个人。

工作表 Demetri 中的数字在 E27 到 E38 的范围内,我想看看工作表 Share_Dump 中 BE4 到 BE163803 范围内的单元格是否在 Demetri 工作表的范围内。

Sub steward_products()
Dim d, s As Worksheet

Set d = Worksheets("Demetri")
Set s = Worksheets("Share_Dump")

For i = 4 To 163803 Step 1
    For j = 27 To 38 Step 1
        If s.Cells(i, 3) = d.Cells(j, 5) Then
            s.Cells(i, 57) = "Demetri"
        End If
    Next j
Next i

1 个答案:

答案 0 :(得分:0)

请试试这个代码。我认为它可以满足您的需求。

Option Explicit

Sub Steward_Products()
    ' 236

    ' use descriptive names and use the declarations to explain them
    ' use Option Explicit and capitalization to avoid typos
    Dim WsSteward   As Worksheet                ' Demetri
    Dim WsDump      As Worksheet                ' Share_Dump
    Dim Fnd         As Range

    Set WsSteward = Worksheets("Demetri")
    Set WsDump = Worksheets("Share_Dump")

    With WsDump
        ' presuming that columns 28:38 are not longer than column 27
        Set Fnd = .Range(.Cells(4, 27), .Cells(.Rows.Count, 27).End(xlUp)) _
                  .Resize(, 12)
        
        Set Fnd = Fnd.Find(WsSteward.Cells(5, "J").Value, _
                           LookIn:=xlValues, LookAt:=xlWhole)
    
        If Fnd Is Nothing Then
            MsgBox "Product """ & WsSteward.Cells(5, 10).Value & """ wasn't found.", _
                   vbInformation, "Invalid product description"
        Else
            .Cells(Fnd.Row, 57) = "Demetri"
        End If
    End With
End Sub