我有一列(列G),我想在其中验证数值是否为数字。如果它们不是数字,我想在A行中粘贴一条错误消息。运行代码时我不会收到任何错误,但是即使单元格中有数字,它也似乎会打印错误消息。
Dim cell As Range
Dim lastRow As Long
lastRow = Range("G" & Rows.Count).End(xlUp).row
For Each cell In Range("G2:" & "G" & lastRow)
If IsNumeric(Range("G2:" & "G" & lastRow)) = True Then cell.Offset(0, -6).Value = cell.Offset(0, -6).Value & ", G is not a number"
Next
End Sub
答案 0 :(得分:3)
通过条件遍历单元格可以这样做:
Sub TestMe()
Dim cell As Range
Dim lastRow As Long
lastRow = Worksheets(1).Range("G" & Rows.Count).End(xlUp).Row
For Each cell In Worksheets(1).Range("G2:" & "G" & lastRow)
If IsError(cell) Then
cell.Offset(0, -6).Value = cell.Address & " is error!"
ElseIf Not IsNumeric(cell.Value) Then
cell.Offset(0, -6).Value = cell.Value & " is not a number"
End If
Next
End Sub
按照Worksheets(1).Range...
的方式引用父级工作表是一个好习惯。