【问题标题】:How to search a certain value and copy the results to other sheet with VBA如何使用 VBA 搜索某个值并将结果复制到其他工作表
【发布时间】:2017-09-25 09:12:26
【问题描述】:

我正在尝试编写 VBA 代码。 我在 excel 中有 2 个工作表:

第一张表:包含我所有工作结果的“init 的结果”

第二张表:“结果标签”

我试图在名为 Id 的第一行中找到某个值,在 Id 列中找到两个特定的 ID 号(86 和 66)并将结果(位于右侧的两列)复制到第二张表一个特定的细胞。

谢谢大家!

【问题讨论】:

  • 查看名为 VLOOKUP 的内置函数,它正是完成这项工作。

标签: vba excel


【解决方案1】:

试试这个

Sub Demo()
    Dim srcSht As Worksheet, destSht As Worksheet
    Dim srcLR As Long, destLR As Long
    Dim cel As Range, srcRng As Range

    Set srcSht = ThisWorkbook.Sheets("Results for init")
    Set destSht = ThisWorkbook.Sheets("Result Tab")

    With srcSht
        srcLR = .Cells(.Rows.Count, "C").End(xlUp).Row  'get last row with data in srcSht using Column C
        Set srcRng = .Range("C2:E" & srcLR)             'set range for look up
    End With

    With destSht
        destLR = .Cells(.Rows.Count, "A").End(xlUp).Row 'get last row with data in destSht using Column A

        For Each cel In .Range("A2:A" & destLR)         'loop through each cell in Column a of destSht
            cel.Offset(0, 1).Value = WorksheetFunction.VLookup(cel, srcRng, 3, False)   'get vlookup result
        Next cel
    End With
End Sub

使用公式的解决方案:

假设您的数据在工作表Results for init 中,然后在工作表Result tab 的Cell B2 中输入以下公式

=VLOOKUP(A2,'Results for init'!$C$2:$E$10,3,FALSE)

或

=INDEX('Results for init'!$E$2:$E$10,MATCH(Sheet3!A2,'Results for init'!$C$2:$C$10,0))

根据需要拖动/复制公式。根据您的数据更改范围2:10。参考图片。

结果标签工作表

【讨论】:

  • 谢谢,运行时错误 1004:无法获取 WorkSheetFunction 类的 Vlookup 属性
  • @Timor - 我在发布之前测试了代码,应该可以工作。发生错误时您能否检查cel 的值以及srcRng.Address 的值
猜你喜欢
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多