首页 > 解决方案 > VBA - 如何编写具有两个条件的 if 语句

问题描述

我正在尝试编写一个简短的 vba,以说明 A 列是否为数字(非空)且 B 列是否为文本-“已关闭”,C 列返回为当前日期。我在下面使用的代码似乎不起作用。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim Cell As Range

For Each Cell In Target
    If Cell.Column = Range("A:B").Column Then
          If Cells(Cell.Row, "A").Value <> "" And Cells(Cell.Row, "B").Value = "closed" Then
               Cells(Cell.Row, "C").Value = Int(Now)
          Else
               Cells(Cell.Row, "C").Value = ""
          End If
    End If
Next Cell

End Sub

有什么帮助吗?

标签: vba

解决方案


你能试试这个吗?我认为您检查该列的语法已关闭。Range("A:B").Column将返回 1。

此外,这会显式检查 A 列中的数字,而不仅仅是非空白。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim Cell As Range

For Each Cell In Target
    If Cell.Column = 1 Or Cell.Column = 2 Then
          If Len(Cells(Cell.Row, "A").Value) > 0 And IsNumeric(Cells(Cell.Row, "A").Value) And Cells(Cell.Row, "B").Value = "closed" Then
               Cells(Cell.Row, "C").Value = Int(Now)
          Else
               Cells(Cell.Row, "C").Value = vbNullString
          End If
    End If
Next Cell

End Sub

推荐阅读