简体   繁体   中英

How to check the value of Σ character in an Excel Cell? - VBA

I do have a cell in excel that contains Σh. Not sure how to check for it in vba. I have tried with .Value and .Text , but the check is never true.

在此处输入图像描述

If (tRange.Value = (ChrW(931) + "h")) Then
    Exit Sub
End if

When testing (Debug) I get this result for ActiveCell.Value = Sh

在此处输入图像描述

(a) You have to use .Value to get the content of the cell.
(b) You should use the ampersand character ( & ) to concatenate strings in VBA. The plus-sign works also, but only if all operands are strings.
(c) ChrW(931) & "h" (or ChrW(931) + "h" ) should work. VBA is able to handle characters even if the VBA-environment cannot show them.

Seems to me that either the Sigma-character is composed with a different character, or your cell contains invisible characters like space, newline, tabs...

You can dump the content of the cell with the following code to get an idea why your If -statement fails:

Sub DumpString(s As String)
    Dim i As Long
    For i = 1 To Len(s)
        Dim c As String
        c = Mid(s, i, 1)
        Debug.Print i, AscW(c), c
    Next
End Sub

When you enter the following command into the immediate window , you will see output like that:

 DumpString activecell.Value
   1             931          S
   2             104          h

This should check if cell value contains the sub-string 'Σh'

If tRange.Value Like "*" & ChrW(931) & "h*" Then
    Exit Sub
End If

Another maybe simpler way for some folks

If InStr(1, tRange.Value, ChrW(931) & "h") <> 0 Then
    Exit Sub
End If

You have to use an ampersand to join the two characters:

If (tRange.Value = ChrW(931) & "h") Then
    Exit Sub
End if

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM