首页 > 解决方案 > VBA从不同位置提取相等的值

问题描述

这就是我目前在这个项目中想要实现的目标。在场景中,我在黄色位置标识了一个库存为零的项目,我需要搜索相同项目、类别但我不想看到的位置网络(数据是从主数据源中提取的)黄色位置,因为我已经知道黄色的库存为零

在此处输入图像描述

标签: vba

解决方案


@Raj 我不确定你的意思,但我尝试创建一个代码。

表 1

在此处输入图像描述

  1. 结构包括搜索引擎(黄色区域)和结果)
  2. 您只需在黄色字段上导入数据
  3. 代码运行的地方会擦除结果以带来新的结果。

表 2

在此处输入图像描述

结构(包括数据库)

尝试:

Option Explicit

Sub Test()

    Dim LastRow2 As Long
    Dim i As Long
    Dim Mat_Cat_Loc As String
    Dim LastRow1 As Long

    With Sheet1

        If .Range("B2").Value = "" Or .Range("B3").Value = "" Or .Range("B4").Value = "" Then '<= if some search part missing end sub
            Exit Sub
        End If

        Mat_Cat_Loc = .Range("B2").Value & .Range("B3").Value & .Range("B4").Value ' <= Create Mat_Cat_Loc for the search product

        LastRow1 = .Range("A" & Rows.Count).End(xlUp).Row

        .Range("A8:D" & LastRow1).Clear '<= Clear range from the previous search

    End With

    With Sheet2

        LastRow2 = .Range("A" & Rows.Count).End(xlUp).Row

        For i = 3 To LastRow2 ' <= Loop in Sheet2 and if Mat_Cat_Loc (From the search) does not match Mat_Cat_Loc (From the data does not copy the line to Sheet1 Rsult Table)
            If (.Range("D" & i).Value <> Mat_Cat_Loc) And (.Range("C" & i).Value) <> Sheet1.Range("B4").Value Then
                With Sheet1
                    LastRow1 = .Range("A" & Rows.Count).End(xlUp).Row
                    .Range("A" & LastRow1 + 1).Value = Sheet2.Range("A" & i).Value
                    .Range("B" & LastRow1 + 1).Value = Sheet2.Range("B" & i).Value
                    .Range("C" & LastRow1 + 1).Value = Sheet2.Range("C" & i).Value
                    .Range("D" & LastRow1 + 1).Value = Sheet2.Range("D" & i).Value
                End With
            End If
        Next i
    End With

End Sub

推荐阅读