我在电子表格中有两列,即列(A)和列(B)。
列(A)包含从查询中提取的名称(例如Brian,Bob,Bill等),列(B)包含三种状态之一(已分配,进行中或待处理)。
但是,此查询有时会拉出一些显示“已分配”状态的行,而没有名称,因此代表列(A)中名称的相应单元格为空。因此,我用“未知”手动填充了这些空单元格。
我想做的是创建一个宏,该宏查找(A)列中的每个空单元格,如果右侧的单元格包含“Assinged”一词,则填写单词“Unknown”。
因此条件是:
这是我的代码:
Private Sub CommandButton2_Click()
For Each cell In Columns("A")
If ActiveCell.Value = Empty And ActiveCell.Offset(0, 1).Value = "Assigned" Then ActiveCell.Value = "Unknown"
Next cell
End Sub
最佳答案
欢迎来到SO。
试试这个代码。它会更快地工作,并且应该为您提供所需的东西。
更新:使代码更具防弹性!
Private Sub CommandButton2_Click()
Dim cel As Range, rngFind As Range, rngFilter As Range
Dim wks As Worksheet
Set wks = Sheets("sheet1")
With wks
'-> Error check to make sure "blanks" exist
Set rngFind = .Range("A1:A" & .Range("B" & Rows.Count).End(xlUp).Row).Find("", lookat:=xlWhole)
If Not rngFind Is Nothing Then
Set rngFilter = .Range("A1:B" & .Range("B" & Rows.Count).End(xlUp).Row)
rngFilter.AutoFilter 1, "="
'-> Error check to make sure "assigned" exists for blank cells
Set rngFind = .Columns("B:B").SpecialCells(xlCellTypeVisible).Find("Assigned", lookat:=xlWhole)
If Not rngFind Is Nothing Then
'-> okay, it exists. filter and loop through cells
rngFilter.AutoFilter 2, "Assigned"
Set rngFind = Intersect(.UsedRange, .UsedRange.Offset(1), .Columns(1)).SpecialCells(xlCellTypeVisible)
For Each cel In rngFind
If cel.Offset(0, 1).Value = "Assigned" Then cel.Value = "Unknown"
Next cel
End If
End If
End With
End Sub