excel 将RIGHT函数放在IF语句中时不起作用

iyfjxgzm  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(199)

我想使用RIGHT函数创建一个IF条件。它将查找单元格中的最后4位数字,并将其与另一个单元格进行比较,如果匹配,则执行操作。
下面是我所使用的代码的简化版本。在此体验中要执行的操作只是在单元格中显示计数器。

Public vCounter

Sub Counter()

vCounter = 0

Sheets.Add.Name = "Test"

'The cells the RIGHT function will operate from (A1, A2 and A3)
Sheets("Test").Range("A1") = "123"
Sheets("Test").Range("A2") = "456"
Sheets("Test").Range("A3") = "789"

'The cells the result of the RIGHT function will be compared to (B1, B2 and B3)
Sheets("Test").Range("B1") = "23"
Sheets("Test").Range("B2") = "456"
Sheets("Test").Range("B3") = "89"

'This cell (G3) shows the result of a RIGHT function, considering the
'last two digits in A1, as an experience; it works.
Sheets("Test").Range("G3") = Right(Sheets("Test").Cells(1, 1), 2)

For i = 1 To 3

'The RIGHT function considers the two last digits of, successively,
'A1, A2 and A3, and those are compared to, respectively, 
'B1, B2 and B3. For some reason, it doesn't work here.
    If Right(Sheets("Test").Cells(i, 1), 2) = Sheets("Test").Cells(i, 2) Then
        vCounter = vCounter + 1
    End If
Next i

'This cell (E3) shows the counter, to test whether or not the If
'condition with the RIGHT function works. By changing the contents
'of the cells I compare between each other, I can check whether or
'not it counts correctly. 
Sheets("Test").Range("E3") = vCounter

End Sub

我得到的结果是:The sheet that I get when I run this procedure
总之,在这次实验中,RIGHT函数不起作用,因为vCounter没有达到2。它停留在0,表明它根本不计数。我从这个结果推断,问题在于包含RIGHT函数的IF语句。也许For循环与此有关,但我对此表示怀疑。
有什么想法吗?

yzxexxkh

yzxexxkh1#

即使向工作表中写入字符串值,Excel也会自动假定它们是数值,因此当您读回它们时,将得到Variant/Double类型的值。
如果你通过Right()传递其中一个Double,它会返回一个Variant\String,这是Variant\String和Variant\Double之间的比较,似乎失败了。
部分测试代码:

Sub Tester()
    
    Dim ws As Worksheet, v As Variant
    Set ws = ThisWorkbook.Worksheets("Test")
    
    ws.Range("A1").Value = "123"
    ws.Range("B1").Value = "23"
    
    'Comparing values...
    Debug.Print Right(ws.Range("A1").Value, 2) = ws.Range("B1").Value '>> False (Variant\String vs Variant\Double)
    
    Debug.Print Right(ws.Range("A1").Value, 2) = CStr(ws.Range("B1")) '>> True (Variant\String vs Variant\String)
    
End Sub

相关问题