首页 > 解决方案 > If 语句遍历 VBA 宏的列

问题描述

如果在第一列的特定单元格中遇到参数,我想创建一个宏来遍历列并更改单独列中的值。这是我所拥有的:

If Range(AB) <> 0 Then
    AD = "Basketball"
Else
    AD = "Football"
End If

如何在遍历整个列时将单元格的范围设置为通用的?

标签: excelvba

解决方案


请注意,这也可以使用公式来完成,并且不需要 VBA。在大多数情况下,公式比使用 VBA 更快,因为 VBA 不支持多线程。

公式

因此,只需在 AD 列中添加此公式:

=If(AB:AB<>0, "Basketball", "Football")

VBA

一般结构将使用For循环:

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1") 'reference your sheet

Dim LastRow As Long  'find last used row in column A. Adjust column to your needs
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

Dim iRow As Long
For iRow = 1 To LastRow  'loop from first to last row and do the following in each row
    If ws.Cells(iRow, "AB").Value <> 0 Then
        ws.Cells(iRow, "AD").Value = "Basketball"
    Else
        ws.Cells(iRow, "AD").Value = "Football"
    End If
Next iRow

推荐阅读