You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用VBA为Excel同一列指定空白单元格填充对应区域最小值

问题描述

我有包含如下数据的Excel表格:

Input Output

| Column A | Column B | | Column A | Column B |
| -------- | -------- | | -------- | -------- |
| larry | | | larry | |
| larry | | | larry | 100 |
| 130 | 200 | | 130 | 200 |
| 130 | 100 | | 130 | 100 |
| josh | | | josh | |
| josh | | | josh | 333 |
| 110 | 500 | | 110 | 500 |
| 110 | 459 | --> | 110 | 459 |
| 110 | 333 | | 110 | 333 |
| chris | | | chris | |
| chris | | | chris | 30 |
| 120 | 222 | | 120 | 222 |
| 120 | 111 | | 120 | 111 |
| 120 | 77 | | 120 | 77 |
| 120 | 56 | | 120 | 56 |
| 120 | 30 | | 120 | 30 |

需要使用VBA实现:为Column B中从下往上数第一个空白单元格,填充其下方与该单元格Column A值相同的区域中的最小值(该最小值始终位于对应区域的最后一行)。

我已能从底部开始用下方紧邻值填充所有空白单元格,但不知如何选取区域最小值并填充特定空白单元格,恳请帮助。


解决方案

以下是实现需求的VBA代码,核心逻辑是从表格底部向上遍历定位目标空白单元格,匹配对应A列值的区域后提取最小值填充:

Sub FillBottomBlankWithMin()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim currentRow As Long
    Dim targetAValue As String
    Dim matchRange As Range
    Dim minCellValue As Variant
    
    ' 指定操作的工作表,可根据实际修改为Sheet1等
    Set ws = ThisWorkbook.ActiveSheet
    ' 获取A列数据的最后一行行号
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    ' 从底部向上遍历,寻找B列第一个空白单元格
    For currentRow = lastRow To 1 Step -1
        If IsEmpty(ws.Cells(currentRow, "B").Value) Then
            targetAValue = ws.Cells(currentRow, "A").Value
            
            ' 查找下方区域中所有A列值匹配的单元格,定位到最后一行(最小值所在行)
            Set matchRange = ws.Range("A" & currentRow + 1 & ":A" & lastRow) _
                .Find(What:=targetAValue, LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlPrevious)
            
            ' 找到匹配区域后,提取对应B列的值填充目标单元格
            If Not matchRange Is Nothing Then
                minCellValue = ws.Cells(matchRange.Row, "B").Value
                ws.Cells(currentRow, "B").Value = minCellValue
            End If
            
            ' 找到第一个目标单元格后退出循环,仅处理从下往上第一个空白
            Exit For
        End If
    Next currentRow
End Sub

代码说明

  1. 定位数据边界:通过Cells(Rows.Count, "A").End(xlUp).Row获取A列有效数据的最后一行,避免遍历无效空行。
  2. 反向查找空白:从表格底部向上循环,确保找到的是B列最靠下的第一个空白单元格。
  3. 匹配对应区域:使用反向Find直接定位下方A列值匹配的最后一行(即题目说明的最小值所在行),无需遍历整个区域。
  4. 填充最小值:提取该最后一行B列的值,填充到目标空白单元格后退出循环,完成单次操作。

若需要批量处理所有符合条件的空白单元格,只需移除代码中的Exit For语句即可。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 16:33:38