【问题标题】:For each loop in VBA Excel对于 VBA Excel 中的每个循环
【发布时间】:2021-07-05 10:07:33
【问题描述】:

我是 VBA 的初学者,我试图遍历指定范围的单元格,该范围输入到用户表单上的 refEdit 中,该范围始终有 2 列,但可以有任意数量的行。第一列是类别,第二列是数值。我想找到特定类别的相应值的总和。例如,每当我在单元格中遇到“咖啡”一词时,我想将其右侧单元格中的值取和并开始将它们相加以打印单元格 C1 中所有咖啡的值。我怎样才能让它工作?

这是我一直在使用的:

dim cell, myRange as Range
dim c as string
dim r as long
Set myRange = Range(RefEdit1.Text)
c = "coffee"
r = 0
For Each cell In myRange
    If VBA.LCase(cell) = VBA.LCase(c) Then
         r = r + ActiveCell.Offset(0, 1).Value
    End If
next cell
range("C1") = r

【问题讨论】:

  • SUMIFSUMIFS 公式不适合这项任务吗?

标签: excel vba for-loop


【解决方案1】:

SumIf 与循环

  • 通常最好避免循环,因为它会减慢代码速度。
  • SumIf 'is' 不区分大小写,因此您也避免使用 'LCase-business'。
  • 在一行中声明变量时,您必须为每个变量“使用As”,否则它将被声明为Variant (cell)。
Option Explicit

Sub testSumIf()
    Dim myRange As Range
    Dim c As String
    Set myRange = Range(RefEdit1.Text)
    c = "coffee"
    Range("C1").Value _
        = Application.SumIf(myRange.Columns(1), c, myRange.Columns(2))
End Sub

Sub testLoop()
    Dim cell As Range, myRange As Range
    Dim c As String
    Dim r As Long
    Set myRange = Range(RefEdit1.Text)
    c = VBA.LCase("coffee")
    For Each cell In myRange.Cells
        If VBA.LCase(cell.Value) = c Then
             r = r + cell.Offset(0, 1).Value
        End If
    Next cell
    Range("C1").Value = r
End Sub

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 2018-10-09
    • 2023-04-02
    • 2018-04-05
    相关资源
    最近更新 更多