[英]For each loop in VBA Excel
我是 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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.