简体   繁体   English

Excel VBA-如何使用For Each…Next语句

[英]Excel VBA - How to use the For Each…Next statement

I'm currently learning VBA by doing, and I'm trying to understand the syntax of the For Each...Next statement. 我目前正在通过练习来学习VBA,并且正在尝试了解For Each ... Next语句的语法。 If the syntax is: 如果语法是:

For Each element In group
[statements]
[Exit For]
[statements]
Next [element]

What sort of variables can you use for "element" and "group", and do you define them? 您可以将哪种变量用于“元素”和“组”,并定义它们? I ask because most of the examples I've found for the function don't define "element". 我问,因为我为该函数找到的大多数示例都未定义“元素”。

Say I have a column full of "a", "b", "c", "d" and "N/A", and I want to determine the number of times each appear in the column. 假设我有一个充满“ a”,“ b”,“ c”,“ d”和“ N / A”的列,我想确定每个出现在该列中的次数。

So far I have the following: 到目前为止,我有以下内容:

Sub Count()

Dim lastRow, aCount, bCount, cCount, dCount, NACount As Long

lastRow = Range("A" & Rows.Count).End(xlUp).Row
aCount = 0
bCount = 0
cCount = 0
dCount = 0
NACount = 0

For Each MyCell In Range("A1:A" & lastRow)
    If MyCell.Value = "a" Then
        aCount = aCount + 1
    ElseIf MyCell.Value = "b" Then
        bCount = bCount + 1
    ElseIf MyCell.Value = "c" Then
        cCount = cCount + 1
    ElseIf MyCell.Value = "d" Then
        dCount = dCount + 1
    ElseIf MyCell.Value = "b" Then
        bCount = bCount + 1
    Else
        NACount = NACount + 1
    End If
Next

End Sub

This give a "Type mismatch" error for If MyCell.Value = "a" Then , though I already know that I must be using a wrong group or array. If MyCell.Value = "a" ThenIf MyCell.Value = "a" Then出现“类型不匹配”错误,尽管我已经知道我必须使用错误的组或数组。

Any help for such a beginner issue is greatly appreciated. 非常感谢您对此类初学者问题的任何帮助。

First things first: 首先要注意的是:

Say I have a column full of "a", "b", "c", "d" and "N/A", and I want to determine the number of times each appear in the column. 假设我有一个充满“ a”,“ b”,“ c”,“ d”和“ N / A”的列,我想确定每个出现在该列中的次数。

You should just use the CountIf function :) 应该只使用CountIf函数:)

But as a learning exercise... Your code is raising an error most likely because of an "Error" value in the sheet/cell being counted. 但是作为一项学习练习,您的代码最有可能引发错误,因为正在计算工作表/单元格中的“错误”值。

You could fix it like 您可以像修复它

If Cstr(MyCell.Value) = "a"...

Make sure to do this for the other conditionals, too, or you could do something like: 确保也对其他条件执行此操作,否则您可以执行以下操作:

For Each myCell In Range("A1:A" & lastRow)
Dim clVal As String
clVal = CStr(myCell)
    If clVal = "a" Then
        aCount = aCount + 1
    ElseIf clVal = "b" Then
        bCount = bCount + 1
    ElseIf clVal = "c" Then
        cCount = cCount + 1
    ElseIf clVal = "d" Then
        dCount = dCount + 1
    ElseIf clVal = "b" Then
        bCount = bCount + 1
    Else
        NACount = NACount + 1
    End If
Next

WHY 为什么

Because MyCell is undeclared, it can be an error type. 由于未声明MyCell ,因此它可以是错误类型。 You can't do a string comparison of an error and a string, so that's raising the Type Mismatch error. 您无法对错误和字符串进行字符串比较,因此会引发Type Mismatch错误。 You can use the CStr function to cast MyCell.Value as a string and that can avoid the error. 您可以使用CStr函数将MyCell.Value为字符串,这样可以避免该错误。

A note on declaring your variables... 关于声明变量的说明...

You should declare ALL of your variables and type them appropriately. 您应该声明所有变量并正确键入它们。 VBA does not support multiple implicit inline declarations like: VBA不支持多个隐式内联声明,例如:

Dim lastRow, aCount, bCount, cCount, dCount, NACount As Long

This is functionaly equivalent to: 这在功能上等同于:

Dim lastRow   'As Variant
Dim aCount    'As Variant
Dim bCount    'As Variant
Dim cCount    'As Variant
Dim dCount    'As Variant
Dim naCount As Long

Which is probably not what you were expecting. 这可能不是您所期望的。 Instead, do: 相反,请执行以下操作:

Dim lastRow as Long, aCount as Long, bCount as Long, _ cCount as Long, dCount as Long, NACount As Long

You should also declare ALL of your variables, always, including your loop iterators, like MyCell . 您还应该始终声明所有变量,包括MyCell这样的循环迭代器。 One way to enforce this is to always put Option Explicit at the top of your module. 强制执行此操作的一种方法是始终将Option Explicit放在模块顶部。 This forces variable declaration, and as such, raises a compile error if you have misspelled variable name somewhere, etc. (this is super-common, actually, so always use Option Explicit!, it will save you a lot of hair-pulling). 这会强制进行变量声明,因此,如果您在某处使用了错误拼写的变量名,则会引发编译错误。(这是非常常见的,实际上,因此始终使用Option Explicit !,它将为您节省很多麻烦。) 。

Loop iterators can be of type Variant or they must match a type that is iterable in the collection/array, eg: 循环迭代器可以是Variant类型,或者它们必须与在集合/数组中可迭代的类型匹配,例如:

Dim ws as Worksheet
For each ws in ThisWorkbook.Worksheets
    Debug.Print ws.Name
Next

Or they can be a long/integer for an indexed collection 或者它们可以是索引集合的long / integer

Dim w as Integer
For w = 1 to ThisWorkbook.Worksheets.Count
    Debug.Print w
Next

Also, review the documentation: 另外,请查看文档:

http://msdn.microsoft.com/en-us/library/office/gg264596(v=office.15).aspx http://msdn.microsoft.com/zh-CN/library/office/gg264596(v=office.15).aspx

Ultimately what method you use to iterate depends on what you're trying to accomplish and the structures of the data you're working with. 最终,您使用哪种迭代方法取决于您要完成的工作以及要使用的数据的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM