且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查找一列中具有相同值的单元格,并从同一行的不同列中返回值

更新时间:2022-12-12 07:50:24

下面是使用范围变量的示例.

Here's an example using range variables.

您将要为输入数据范围定义一个范围,并为输出数据定义一个范围.然后在VBA中,您需要将 wrk inRng outRng 变量更改为您定义的命名范围,并更改其中的列索引 for if 块以匹配您要查找的数据的列索引.

You'll want to define a range for the input data range and a range for the output data. Then in the VBA you will want to change the wrk, inRng and outRng variables to be the named ranges you defined and change the column indexes in the for and if blocks to match the column index of the data you are looking for.

Option Explicit
Option Base 1

Sub FindValues()
    Dim wrk As Worksheet
    Dim inRng As Range
    Dim outRng As Range

    Dim cntr As Long
    Dim outCntr As Long
    Dim findVal As Double

    Set wrk = Worksheets("Data")
    Set inRng = wrk.Range("LookupRange")
    Set outRng = wrk.Range("OutputRange")

    ' Clear the output range in case you have fewer values on this run than on the previous one
    outRng.ClearContents

    ' Set the value you are looking for
    findVal = 1

    ' Iterate through the rows in the input range.  If you find the result you want then write it to the output range
    For cntr = 1 To inRng.Rows.Count
        If inRng(cntr, 1) = findVal Then ' Assumes the value you are finding is in column 1 of the input range
            outRng(outCntr, 1) = inRng(cntr, 2) ' Assumes the values you are exporting is in column 2 of the input range
            outCntr = outCntr + 1
        End If
    Next cntr
End Sub