我目前有3个宏可用于第一行。我将它们附在下面。现在,我想创建一个循环,以使该代码在所有行中运行,直到输入的最后一行为止。当在B,D和E列中找到一个空单元格时,它将打印出缺少的内容。(我最终会将这三个宏放入一个,以使其更加简洁)
这是第一行的正确代码
Sub error_field()
Sheets("1099-Misc_Form_Template").Select
Range("A2").Select
If Range("A2").Value = "" Then
ActiveCell.Value = ActiveCell.Value & "PayorID"
End If
End Sub
'checking if TIN is empty
Sub error_field2()
Sheets("1099-Misc_Form_Template").Select
Range("A2").Select
If Range("E2").Value = "" Then
ActiveCell.Value = ActiveCell.Value & ", TIN"
End If
End Sub
'checking if AccountNo is empty
Sub error_field3()
Sheets("1099-Misc_Form_Template").Select
Range("A2").Select
If Range("F2").Value = "" Then
ActiveCell.Value = ActiveCell.Value & ", AccountNo"
End If
End Sub
这是我尝试过的循环:
'repeating for all rows
Sub repeat_all_rows()
Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer
RowCount = 0
Set sh = ActiveSheet
For Each rw In sh.Rows
If Range("A2").Value = "" Then
ActiveCell.Value = ActiveCell.Value & "PayorID"
If Range("E2").Value = "" Then
ActiveCell.Value = ActiveCell.Value & ", TIN"
If Range("F2").Value = "" Then
ActiveCell.Value = ActiveCell.Value & ", AccountNo"
Exit For
End If
RowCount = RowCount + 1
Next rw
End Sub
我想要对所有行执行的代码,直到找到最后一行数据为止。 对我好一点,我是一个初学者,所以我知道我的代码很烂。
答案 0 :(得分:1)
类似的事情应该起作用:
'repeating for all rows
Sub repeat_all_rows()
Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer
RowCount = 0
Set sh = ActiveSheet
For Each rw In sh.UsedRange.Rows
FlagMissing rw, "A", "Payor ID"
FlagMissing rw, "E", "TIN"
FlagMissing rw, "F", "AccountNo"
Next rw
End Sub
Sub FlagMissing(rw As Range, col as String, Flag As String)
If Len(Trim(rw.cells(1, col).value)) = 0 Then
With rw.Cells(1)
'add the flag with a comma if there's already content there
.Value = .Value & IIf(.Value="", "", ", ") & Flag
End with
End If
End sub
...尽管我没有在您发布的代码中说明该Exit For
。