对排除某些值的变量范围求和VBA

问题描述 投票:0回答:2

我是 VBA 新手,正在尝试创建工作报告模板。我还想看看如何根据我个人的理解对其进行编码,而不是使用公式。

简单地说,我在

column A
中有一组可变的值,在
column B
中有日期。
Column D
是可变的日期范围(用户输入。我希望将其作为我的代码中的数组。)

我想对

column A
求和,同时排除
column D
中指定的日期,并将此总和输出到单元格
G1
中。我在下面附上了一张图片。

提前致谢!

床单图片

vba excel
2个回答
0
投票

尝试一下这段代码,这是不言自明的。

Sub sumVariables()
Dim i As Long, j As Long, sum As Long, match As Boolean
sum = 0
match = False
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
    For j = 2 To Cells(Rows.Count, 4).End(xlUp).Row
        If Cells(i, 2) = Cells(j, 4) Then
            match = True
        End If
    Next j
    If match = False Then
        sum = sum + Cells(i, 1)
    End If
    match = False
Next i
Cells(1, 7) = sum
End Sub

此代码适用于工作表中的 n 行,并在

G1
中给出总数。如果您需要任何帮助,请告诉我。


0
投票
Sub Formula_Values()
Dim cell As Range, ws As Worksheet, rngFormulas As Range
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
For Each ws In Worksheets
    On Error Resume Next
    Set rngFormulas = ws.Cells.SpecialCells(xlCellTypeFormulas)
    On Error GoTo 0
    If Not rngFormulas Is Nothing Then
        For Each cell In rngFormulas
            If InStr(1, cell.Formula, "=SUM", 0) = 0 Then cell.Value = cell.Value
        Next cell
    End If
Next ws
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
MsgBox "Formulas converted to values excluding 'SUM' formulas.", vbInformation, ""

结束子

块引用

© www.soinside.com 2019 - 2024. All rights reserved.