我想使用 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
這是我得到的: 運行此程序時得到的作業表
總之,在這種體驗中,RIGHT 函式不知何故不起作用,因為 vCounter 沒有達到 2。它保持在 0,表明它根本不重要。我從這個結果推斷出問題出在包含 RIGHT 函式的 IF 陳述句中。也許 For Loop 與它有關,但我對此表示懷疑。
有什么想法嗎?
uj5u.com熱心網友回復:
即使您將字串值寫入作業表,Excel 也會自動將它們假定為數值,因此當您讀回它們時,您將獲得 Double 型別的值。
但是,如果您傳遞其中一個 Double Right()
,它將回傳一個 String,而 String 和 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"
Debug.Print TypeName(ws.Range("A1").Value), _
TypeName(ws.Range("B1").Value) '>> Double / Double
Debug.Print TypeName(Right(ws.Range("A1").Value, 2)) '>> String (not Variant?)
'Comparing values...
Debug.Print Right(ws.Range("A1").Value, 2) = ws.Range("B1").Value '>> False (String vs Double)
Debug.Print Right(ws.Range("A1").Value, 2) = CDbl(ws.Range("B1").Value) '>> True (why though?)
Debug.Print Right(ws.Range("A1").Value, 2) = CStr(ws.Range("B1")) '>> True (String vs String)
End Sub
注意 - 我希望前兩個值比較是等效的,但它們給出False
了True
. 有人知道為什么嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/536509.html
標籤:擅长VBAexcel公式
上一篇:跳轉到檔案中找到的文本
下一篇:Vba二維陣列根據陣列索引排序