从Formula返回错误的值

时间:2015-12-16 20:26:01

标签: excel vba excel-vba

您好我正在处理一个创建两列的宏,并在每行中使用公式IF填充它们。

公式中要比较的值在宏中从其他列返回,变量为Rfind,Rfind1,Rfind2。那些细胞含有日期。并且必须返回“审核”或“禁用”。问题是,公式返回错误的值。例如,如果第一个单元格包含01/10/2015而另一个单元格包含09/08/2013,则它仍会返回“已禁用”。什么时候应该是评论。

任何想法?

这是整个宏。

Sub test()


Dim LastRow As Long
LastRow = Cells.Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Dim rFind As Range
With Range("A:DB")
        Set rFind = .Find(What:="Account Last Updated", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
        If Not rFind Is Nothing Then
End If
End With

 Dim rFind1 As Range

    With Range("A:DB")
        Set rFind1 = .Find(What:="Termination Date", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
        If Not rFind1 Is Nothing Then

        End If
    End With

    Dim rFind2 As Range

    With Range("A:DB")
        Set rFind2 = .Find(What:="Last Password set date", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
        If Not rFind2 Is Nothing Then
        End If
    End With


x = ActiveSheet.UsedRange.Columns.Count
ActiveSheet.Cells(1, x + 1) = "Account last updated after termination"
intCounter = 2
While (intCounter < LastRow)
    ActiveSheet.Cells(intCounter, x + 1).Formula = "=IF(" & Chr(34) & Cells(intCounter, rFind2.Column) & Chr(34) & ">=" & Chr(34) & Cells(intCounter, rFind1.Column) & Chr(34) & ",""review"",""old"")"
    intCounter = intCounter + 1
Wend

Dim x As Integer
x = ActiveSheet.UsedRange.Columns.Count
ActiveSheet.Cells(1, x + 1) = "Password After Termination"
intCounter = 2
While (intCounter < LastRow)
    ActiveSheet.Cells(intCounter, x + 1).Formula = "=IF(" & Chr(34) & Cells(intCounter, rFind.Column) & Chr(34) & ">=" & Chr(34) & Cells(intCounter, rFind1.Column) & Chr(34) & ",""review"",""disabled"")"
    intCounter = intCounter + 1
Wend

End Sub

1 个答案:

答案 0 :(得分:1)

我不确定为什么你混合了“”和CHR(34),我个人总是喜欢“”和“”“但是你的电话,你需要插入TEXT公式来暗示你要比较的数据是什么否则它只是假设它是文本字符串比较,它不会将其视为日期。

试试这个:

"=IF(TEXT(""" & Cells(intcounter, rFind.column) & """,""DD/MM/YYYY"")>=TEXT(""" & Cells(intcounter, rFind1.column) & """,""DD/MM/YYYY""),""review"",""disabled"")"

它在我的测试中起作用

Sub DateStringCompare()
Dim rFind As Range, rFind1 As Range, intcounter As Long
intcounter = 1
Set rFind = Range("B2")
Set rFind1 = Range("C2")
Range("B1").Formula = "15/10/2015" 'You may need to change this depending on your 
Range("C1").Formula = "15/11/2015" 'You may need to change this depending on your 
Range("D1").Formula = "=IF(TEXT(""" & Cells(intcounter, rFind.column) & """,""DD/MM/YYYY"")>=TEXT(""" & Cells(intcounter, rFind1.column) & """,""DD/MM/YYYY""),""review"",""disabled"")"
Range("D2").Formula = "=IF(TEXT(""" & Cells(intcounter, rFind.column) & """,""DD/MM/YYYY"")<=TEXT(""" & Cells(intcounter, rFind1.column) & """,""DD/MM/YYYY""),""review"",""disabled"")"
End Sub