Excel VBA 技巧:一键提取收入 & 支出数据并求和

Excel VBA 技巧:一键提取收入 & 支出数据并求和

编码文章call10242025-05-21 12:30:5913A+A-

在 Excel 处理数据时,我们经常会遇到这样的情况:一列文本数据中包含 收入支出 信息,如何 精准提取 其中的数值,并分别计算总金额呢?今天,我们来看看如何用 VBA 来完成这个过程,一键自动填充数据!

我们有一个 Excel 表格,D列 记录了一些收入和支出的详细信息,如下图所示

我们希望:

1、提取收入中的数值 并计算总和

2、提取支出中的数值 并计算总和

3、自动填入 B列(收入总计)和 C列(支出总计)

以下是完整的 VBA 脚本,可以自动处理 D列数据,并将结果填入 B列(收入)和 C列(支出)

Sub ExtractAndSumIncomeExpense()
    Dim ws As Worksheet
    Dim rng As Range, cell As Range
    Dim lastRow As Long
    Dim incomeTotal As Double, expenseTotal As Double
    Dim incomePart As String, expensePart As String
    Dim incomeValues() As String, expenseValues() As String
    Dim i As Integer
    
    Set ws = ActiveSheet
    lastRow = ws.Cells(ws.Rows.Count, 4).End(xlUp).Row ' 动态获取D列最后一行
    Set rng = ws.Range("D2:D" & lastRow) ' 设定范围
    
    For Each cell In rng
        incomeTotal = 0
        expenseTotal = 0
        
        ' 提取收入和支出部分
        If InStr(cell.Value, "收入:") > 0 Then
            incomePart = Split(cell.Value, "收入:")(1)
            incomePart = Split(incomePart, "支出:")(0) ' 仅获取收入部分
            incomeValues = Split(incomePart, "+")
            
            ' 计算收入总和
            For i = LBound(incomeValues) To UBound(incomeValues)
                incomeTotal = incomeTotal + ExtractNumber(incomeValues(i))
            Next i
        End If
        
        If InStr(cell.Value, "支出:") > 0 Then
            expensePart = Split(cell.Value, "支出:")(1)
            expenseValues = Split(expensePart, "+")
            
            ' 计算支出总和
            For i = LBound(expenseValues) To UBound(expenseValues)
                expenseTotal = expenseTotal + ExtractNumber(expenseValues(i))
            Next i
        End If
        
        ' 结果填入 B列(收入) & C列(支出)
        ws.Cells(cell.Row, 2).Value = incomeTotal
        ws.Cells(cell.Row, 3).Value = expenseTotal
    Next cell
End Sub

' 提取字符串中的数值
Function ExtractNumber(ByVal txt As String) As Double
    Dim regex As Object
    Set regex = CreateObject("VBScript.RegExp")
    
    With regex
        .Pattern = "\d+\.?\d*" ' 提取整数或小数
        .Global = True
    End With
    
    If regex.Test(txt) Then
        ExtractNumber = CDbl(regex.Execute(txt)(0))
    Else
        ExtractNumber = 0
    End If
End Function

代码解析

1、动态获取数据范围:lastRow = ws.Cells(ws.Rows.Count, 4).End(xlUp).Row

2、精准拆分收入 & 支出:使用 Split 识别 收入: 和 支出:

3、 正则表达式提取数值:ExtractNumber 过滤文本,只保留纯数字

4、自动填充 B列 & C列:无需手动操作,一键完成计算

动图演示:

这段 VBA 代码可以帮你快速提取并计算收入和支出数据,如果你对 Excel 自动化感兴趣,不妨尝试应用到自己的表格中!有任何问题或优化建议,欢迎交流~

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4