基于SKU、价格及日期范围比对两个Excel工作表,高亮不匹配项
工作表信息
Sheet 1: sell_in
| 列 | 名称 | 示例 |
|---|---|---|
| A | SKU | 12345 |
| B | Price(价格) | 59990 |
| C | Start Date(开始日期) | 01-09-2024 |
| D | End Date(结束日期) | 30-09-2024 |
Sheet 2: oficial_prices
| 列 | 名称 | 示例 |
|---|---|---|
| A | SKU | 12345 |
| B | Price(价格) | 59990 |
| C | Start Date(开始日期) | 01-09-2024 |
| D | End Date(结束日期) | 30-09-2024 |
需求目标
验证sell_in中的每一行是否能在oficial_prices中找到至少一行满足以下全部条件:
- SKU与Price必须匹配(单个SKU可能对应多个匹配项);
sell_in的开始日期 ≥oficial_prices的开始日期;sell_in的结束日期 ≤oficial_prices的结束日期。
找到符合条件的行则视为有效;未找到匹配项时,将sell_in对应行的B、C、D列(Price、开始日期、结束日期)单元格标红。
需要一套高效的VBA解决方案,支持遍历两个工作表、单个SKU多匹配项校验及日期逻辑判断。
备注
- 两个工作表均包含数百行数据;
- 日期格式为DD-MM-YYYY;
- 使用Excel版本:Microsoft 365。
VBA解决方案
Sub ValidateSellInData() Dim wsSellIn As Worksheet, wsOfficial As Worksheet Dim sellInData As Variant, officialData As Variant Dim lastRowSellIn As Long, lastRowOfficial As Long Dim i As Long, j As Long Dim isMatchFound As Boolean ' 绑定目标工作表 Set wsSellIn = ThisWorkbook.Worksheets("sell_in") Set wsOfficial = ThisWorkbook.Worksheets("oficial_prices") ' 获取数据最后一行,批量读取数据到数组(减少IO操作,提升效率) lastRowSellIn = wsSellIn.Cells(wsSellIn.Rows.Count, "A").End(xlUp).Row lastRowOfficial = wsOfficial.Cells(wsOfficial.Rows.Count, "A").End(xlUp).Row sellInData = wsSellIn.Range("A1:D" & lastRowSellIn).Value officialData = wsOfficial.Range("A1:D" & lastRowOfficial).Value ' 清除之前的标红格式 wsSellIn.Range("B2:D" & lastRowSellIn).Interior.ColorIndex = xlNone ' 遍历sell_in数据行(跳过表头) For i = 2 To lastRowSellIn isMatchFound = False ' 遍历official_prices数据行(跳过表头) For j = 2 To lastRowOfficial ' 先校验SKU和Price匹配 If sellInData(i, 1) = officialData(j, 1) And sellInData(i, 2) = officialData(j, 2) Then ' 校验日期范围逻辑 If CDate(sellInData(i, 3)) >= CDate(officialData(j, 3)) And CDate(sellInData(i, 4)) <= CDate(officialData(j, 4)) Then isMatchFound = True Exit For ' 找到匹配项立即终止内层循环 End If End If Next j ' 未找到匹配项,标记红色背景 If Not isMatchFound Then wsSellIn.Range("B" & i & ":D" & i).Interior.Color = RGB(255, 153, 153) End If Next i MsgBox "校验完成!未匹配的行已标红。", vbInformation End Sub
代码说明
- 高效性:通过数组批量读取所有数据,避免频繁读写工作表,数百行数据下运行速度显著快于逐单元格读取;
- 逻辑严谨:严格按照需求校验SKU、Price及日期范围,找到匹配项后立即终止内层循环,减少不必要的计算;
- 兼容性:使用
CDate处理日期转换,Excel 365可正确识别DD-MM-YYYY格式; - 易用性:自动识别数据最后一行,无需手动调整范围;运行前自动清除旧格式,避免残留标记。
内容的提问来源于stack exchange,提问作者Francisco Augusto Varela Aguir
相关产品推荐
相关产品推荐

