查找同一行不同列重复项:VBA高亮当日交易行
VBA实现高亮当日交易行并统计占比
核心高亮代码
直接循环逐行对比买入、卖出日期,匹配则高亮整行:
Sub HighlightSameDateTrades() Dim ws As Worksheet Dim lastRow As Long Dim i As Long ' 指定目标工作表,替换为你的表名 Set ws = ThisWorkbook.Worksheets("投资列表") ' 获取数据最后一行(假设买入日期在A列) lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ' 清除原有高亮格式 ws.Cells.Interior.ColorIndex = xlNone ' 从第2行开始遍历(跳过表头) For i = 2 To lastRow ' 对比同一行的买入(A列)和卖出(B列)日期,按需修改列标 If ws.Cells(i, "A").Value = ws.Cells(i, "B").Value Then ' 高亮整行,ColorIndex=6为黄色,可替换为其他值 ws.Rows(i).Interior.ColorIndex = 6 End If Next i End Sub
关键调整点
- 工作表名:把
"投资列表"改成你实际使用的工作表名称 - 列位置:如果买入/卖出日期不在A/B列,替换代码里的
"A"、"B"为对应列标(如"C"、"D") - 高亮颜色:
ColorIndex=6是黄色,可换成ColorIndex=3(红色)或RGB(200,255,200)(浅绿色)等
统计当日交易占比
合并高亮与统计逻辑,直接输出占比:
Sub HighlightAndCalculateRatio() Dim ws As Worksheet Dim lastRow As Long, i As Long Dim sameDateCount As Long, totalTrades As Long Set ws = ThisWorkbook.Worksheets("投资列表") lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row totalTrades = lastRow - 1 ' 减去表头行 ws.Cells.Interior.ColorIndex = xlNone sameDateCount = 0 For i = 2 To lastRow If ws.Cells(i, "A").Value = ws.Cells(i, "B").Value Then ws.Rows(i).Interior.ColorIndex = 6 sameDateCount = sameDateCount + 1 End If Next i ' 将占比写入E1单元格,可修改目标位置 ws.Range("E1").Value = "当日交易占比:" & Format(sameDateCount / totalTrades, "0.00%") End Sub
内容的提问来源于stack exchange,提问作者Don S
相关产品推荐
相关产品推荐

