两个单元格值的比较总是不相等

问题描述 投票:0回答:2

无论出于何种原因,尽管单元格中的值相同,但If zoneChanged.Columns(-5).Value <> correctZone.Columns(2).Value Then语句始终评估为真。也许在这一点上,价值观永远不会相同,但我无法弄清楚原因。此外,返回的结果在两组值之间交替,即使这不是预期的。这是整个代码:

Sub panelSearch()

Dim Pos As Long
Dim i As Long
Dim cellFieldSet As Range
Dim cellSearchSet As Range
Dim cellBeingSearched As Range
Dim cellBeingSearchedFor As Range
Dim zoneChanged As Range
Dim correctZone As Range
Dim interVal As Range
'Area I am attempting to search
Set cellSearchSet = Range("U2:U8184") '8184
'Values I am searching for
Set cellFieldSet = Range("AI2:AI615")
i = 0

For Each cellBeingSearched In cellSearchSet

        For Each cellBeingSearchedFor In cellFieldSet

        Pos = InStr(cellBeingSearched, cellBeingSearchedFor.Value)

             If Pos > 0 Then 'code if found
             Set zoneChanged = cellBeingSearched
             Set correctZone = cellBeingSearchedFor
                    '-4142 is default color index

                 If zoneChanged.Columns(-5).Interior.ColorIndex = -4142 Then
                 'This control statement always evaluates as true even when the two cells should be the same
                    If zoneChanged.Columns(-5).Value <> correctZone.Columns(2).Value Then
                    'Need to add counter to keep multiple results from changing cell multiple times

                    zoneChanged.Columns(-5).ClearContents
                    zoneChanged.Columns(-5) = zoneChanged.Columns(-5) & correctZone.Columns(2)

                    zoneChanged.Columns(-5).Interior.Color = RGB(255, 0, 0)

                        'Counter for multiple results
                        If i > 0 Then
                        zoneChanged.Columns(-5).Interior.Color = RGB(128, 128, 128)
                        End If


                    End If
                      i = i + 1
                 End If

            End If
        Next cellBeingSearchedFor

    Next cellBeingSearched
End Sub
excel vba excel-vba
2个回答
3
投票

现在@DisplayName指出我的解释不正确,我对它有了更深入的了解。然而,解决方案并没有改变,只是我的解释原因。

所以问题中的问题很明显,它只是移动了错误的列数,因为(乍一看)column属性的一个非常奇怪的计数系统(如果我们调查它就不是那么奇怪)。

Counting of Columns

处理行/列计数时,Excel从1开始计数。因此,如果我们做Column(1).Select,它会选择第一列A。因此,我们在column属性中给出的参数是列号(而不是我们想要移动的量)。

因此,因为Column(1)是第一列(例如,所选范围),这意味着Column(0)是第一列(所选范围)的左侧。

因此,如果我们使用column来移动.Columns(-1)将选择2列向左移动,是的我的意思是两个。

Columns(5).Columns(-1).Select 
Debug.Print Selection.Column '= 3

如果我们考虑转移,我们会等待选择第4列(左边一个)。但是它选择列号-1,其中当前列是第1列。因此从1(当前)到-1(目的地)计算它是2左边的1,这就是为什么它将2左移。

结论 我得出结论,Columns()应该用于跳转到特定的列号。但是当我们想要相对于当前选择移位(特定数量的列)时,我们应该使用Offset()进行方便的计数。

Counting of Offset

所以Offset正如预期的那样移动,.Offset(0, -1)将选择1列向左移动(正如-1让我们期待的那样)。

要离开5个细胞,请使用.Offset(0, -5)。同样,.Columns(2)也应该是.Offset(0, 2)

Columns(5).Offset(0, -1).Select
Debug.Print Selection.Column '= 4

有关更多信息,请查看文档:Range.Offset Property (Excel)


1
投票

我相信那是因为你使用负值(-5)作为列的索引。

据我所知,你应该使用正数作为索引。

© www.soinside.com 2019 - 2024. All rights reserved.