比较大于“长整数”的精确整数

时间:2018-06-29 20:32:27

标签: excel vba excel-vba type-conversion comparison

我需要在Excel 2013中找到更好的VBA数据类型,以便可以在两个正的10位整数之间进行更准确的比较。我已经找到并尝试了CULng,但是此版本似乎不存在。另外,CLng没有这些数字所需的范围。

我有一个电话号码数据库(10位数字),需要一种比较两个确切电话号码的方法。我数据库中的某些条目是列出范围的第一个和最后一个字符串,因此我不能仅使用If A = B Then(执行某项操作)。我尝试使用CSng,但是使用指数格式将数字四舍五入(5555559100和5555559150都变为5.555559e + 09)。即使这两个数字不匹配,也将被视为相等。在此代码之前,我将搜索TN剥离为仅数字,但它仍然是字符串值。

Private Sub FindTN()

Dim TN As String
Dim begin  As Single
Dim last As Single
Dim RowNo As Long

Sheet1.Range("A1").Value = "5555559100TO5555559125"
Sheet1.Range("A2").Value = "5555559150TO5555559175"
Sheet1.Range("A3").Value = "5555559160"

TN = "5555559160"

For Each entry In Sheet1.Range("A1:A3")
    If Len(entry.Value) = 10 And entry.Value = TN Then
        RowNo = entry.Row
        Debug.Print "RowNo = " & RowNo

    'Find beginning and ending values of a range
    ElseIf Len(entry.Value) > 10 And InStr(11, entry.Value, "TO") = 11 Then
        begin = CSng(Left(entry.Value, 10))
        last = CSng(Right(entry.Value, 10))

        'Search within range
        If CSng(TN) >= begin And CSng(TN) <= last Then
            RowNo = entry.Row
            Debug.Print "RowNo = " & RowNo
        End If
    End If
Next entry

End Sub

它应该仅在第2行和第3行匹配,但结果是

RowNo = 1
RowNo = 2
RowNo = 3

1 个答案:

答案 0 :(得分:1)

将变量固定为这样的两倍。

Private Sub FindTN()

Dim TN As String
Dim begin  As Double 'Single
Dim last As Double ' Single
Dim RowNo As Long

Sheet1.Range("A1").Value = "5555559100TO5555559125"
Sheet1.Range("A2").Value = "5555559150TO5555559175"
Sheet1.Range("A3").Value = "5555559160"

TN = "5555559160"

For Each entry In Sheet1.Range("A1:A3")
    If Len(entry.Value) = 10 And entry.Value = TN Then
        RowNo = entry.Row
        Debug.Print "RowNo = " & RowNo

    'Find beginning and ending values of a range
    ElseIf Len(entry.Value) > 10 And InStr(11, entry.Value, "TO") = 11 Then
        begin = CDbl(Left(entry.Value, 10))
        last = CDbl(Right(entry.Value, 10))

        'Search within range
        If CDbl(TN) >= begin And CDbl(TN) <= last Then
            RowNo = entry.Row
            Debug.Print "RowNo = " & RowNo
        End If
    End If
Next entry

End Sub