excel - 在与另一列和日期匹配的列中搜索值?

标签 excel vba

我将数据存储在 Excel 的三列中

A 列:序列号
B 栏:日期
C 栏:值(value)(例如成本)

我需要查找与特定序列号(A 列)和日期(B 列)关联的值(C 列)。

例如,在下面的屏幕截图中,如果我想查找与序列号 (T455) 和日期(2010 年 12 月 13 日)关联的值,则该值应为 8。

enter image description here

我能想出的唯一方法是计算效率低下,因为每次查找值时我都会遍历所有单元格。

例如,是否有一种方法可以限制给定序列号的搜索区域?

例如,如果我正在查找序列号 T455 的值,我如何限制代码在行 (6-13) 中搜索日期并在 C 列中找到相应的值,而不是搜索整个表?

Sub FindValue()

Dim S as String
Dim D as Date
Dim V as Integer

S = T455
D = Dec 13, 2010

for i = 1 to Range("A1").End(xldown).Row 

If Range("A" & i) = S And Range("B" & i) < Date - 7 And Range("B" & i) < Date + 7   Then
' This way i search a date range rather than a specific date

V = Range("C" & i).Value

End If

End Sub

我想到了 While 循环或 Lookup 函数,但走到了死胡同。

最佳答案

非 VBA 解决方案可能更容易且不那么令人头疼。

A 列包含公式,A1 = "=B1&C1"

单元格 G1 公式可以在公式栏中看到。

enter image description here

更新
这是一个运行速度更快的 VBA 解决方案,但是根据您所写的内容,有一些我不确定的注释。此外,请查看一些注释以帮助您的代码更符合您的要求。

Sub FindValue()

Dim S As String, D As Date, V As Integer, rngFound As Range, cel As Range

S = "T455" 'needs quotes around the string
D = "Dec 13, 2010" 'needs quotes around the date

Dim wks As Worksheet
Set wks = ActiveSheet

With wks

     'always better to AutoFilter than Loop when you can!
    .UsedRange.AutoFilter 1, S
    .UsedRange.AutoFilter 2, ">" & D - 7, xlAnd, "<" & D + 7

    Set rngFound = Intersect(.UsedRange, .Columns(3)).SpecialCells(xlCellTypeVisible)

    'the only thing here is if you have a date range _
        'you may return more than one result _
        'in that case, I don't know what you want to do with all the V's

    If Not rngFound Is Nothing Then
        For Each cel In rngFound
            V = cel.Value
        Next
    End If

    .AutoFilterMode = False

End With

End Sub

关于excel - 在与另一列和日期匹配的列中搜索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11232210/

相关文章:

excel - 通过VBA打开CSV文件(性能)

Excel VBA保护工作表而不锁定所有单元格

第二次保存为 CSV 文件时 Excel 崩溃

excel - 保存工作簿的 vba 例程没有预期的结果

node.js - 从 S3 下载 xlsx 并解析它

vba - 使用VBA如何调用Adobe Create PDF功能

javascript - 有没有办法在 Office.js Excel 插件中更改线条形状的颜色?

vba - Excel VBA - 范围及其子范围的并集

excel - VBA 代码打开不需要的浏览器窗口

excel - 如果我后来从其中任何一个中删除了任何超链接,为什么excel会删除所有粘贴的超链接?