我试图写一个简短的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
有帮助吗?
答案 0 :(得分:1)
您可以试试吗?我认为您用于检查该列的语法已关闭。 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
答案 1 :(得分:0)
在代码中,检查目标中的每个单元格,然后检查是否要检查它。是的,这听起来令人困惑。
仅查看您要检查的单元格-通过查看Intersect
。
我还重命名了Cell
,因为使用特殊词会使我对意想不到的后果感到担忧。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim RangeToCheck as Range
Dim CellToCheck As Range
Set RangeToCheck = Intersect(Target, Me.Range("A:B")) ' Faster than a loop
If Not RangeToCheck Is Nothing Then
For Each CellToCheck In RangeToCheck
If Me.Cells(CellToCheck.Row, "A").Value <> "" And Me.Cells(CellToCheck.Row, "B").Value = "closed" Then
Me.Cells(CellToCheck.Row, "C").Value = Int(Now)
Else
Me.Cells(CellToCheck.Row, "C").Value = ""
End If
Next CellToCheck
End If ' a simple check, because this event handler might be used for other things too.
End Sub
此代码从根本上还是有缺陷的,因为它没有考虑到多单元或多区域选择。我也没有仔细检查上面的代码,以了解如果RangeToCheck
为Nothing
时会发生什么(我假设For Each
循环将什么都不做,但这是一个假设,我还没有测试代码。
此外,您检查单元的逻辑似乎有些混乱,但是我不知道其背后的业务流程,因此无法提供任何解决方案。
答案 2 :(得分:-2)
dim rng as range, rcell as range
set rng = Thisworkbook.worksheets("yoursheetname").Range("your range")
for each rcell in rng.cells
if ISNULL(rcell.value)= false AND rcell.offset(0,1).value = "closed" then
rcell.offset(0,2).value = date()
end if
next rcell