Excel 2007 vba range.find方法无法找到包含以下内容的单元格:8英寸(2个字符长,发音:8英寸)

Excel 2007 vba range.find method can't locate cell containing: 8" (2 chars long, pronounced: 8 inches)

在电子表格中特定的1列范围内,我需要使用Excel 2007 VBA的range.find方法来定位包含2个字符长值的文本值单元格:8"(在美国发音为8英寸)。 .find方法位于子菜单中,该子菜单可以很好地完成所有其他搜索,但似乎无法找到8",或者实际上找不到任何带双引号的文本值。

在下面的代码中,最初sComparisonText包含8"

我尝试使用Chr(34)sComparisonText的末尾添加1到6个双引号,但是.find方法仍然返回Nothing。

各种搜索都注意到Chr(34)方法,并且还堆叠了双引号:""""解析为"""""""解析为"",依此类推。我还研究了.find方法, 一个特殊的逃脱角色,但那里也没有成功。

1
2
3
4
5
If Right(sComparisonText, 1) ="""" Then
    sComparisonText = sComparisonText & Chr(34) & Chr(34) & Chr(34) & Chr(34) & Chr(34) & Chr(34)
End If
Set rResult = rCT.Columns(InputColumn).Find(What:=sComparisonText, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If (rResult Is Nothing) Then  'Add a new row to the bottom of the rCT range

有人可以告诉我我在做什么错吗?

非常感谢你!
戴夫


目前尚不清楚为什么要尝试转义不是字符串文字的内容。您需要在字符串文字中转义双引号的原因是编译器可以解析它。如果仅寻找单个",则.Find函数仅期望单个"。如果您已经有一个字符串存储在该字符串中包含"的变量中,请使用该字符串。如果需要在字符串中添加一个,则可以使用Chr$(34)或转义的字符串文字""""。它们给您完全相同的结果字符串:

1
2
3
4
5
6
7
8
Dim sComparisonText As String
Dim rResult As Range

sComparisonText = 8 & Chr$(34)
Set rResult = ActiveSheet.Cells.Find(What:=sComparisonText, LookIn:=xlValues, _
              LookAt:=xlWhole, SearchOrder:=xlByColumns, _
              SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
Debug.Print rResult.Address

...是相同的...

1
2
3
4
5
sComparisonText ="8"""
Set rResult = ActiveSheet.Cells.Find(What:=sComparisonText, LookIn:=xlValues, _
              LookAt:=xlWhole, SearchOrder:=xlByColumns, _
              SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
Debug.Print rResult.Address

...是相同的...

1
sComparisonText = 8 &""""

...等等。

转义序列在编译器外部没有任何意义。


首先要考虑的是使用xlPart而不是xlWhole

第二件事是验证您是否确实有双引号而不是一对单引号。单击错误的单元格并运行:

1
2
3
4
5
6
7
8
9
10
11
12
Sub WhatIsInThere()
    Dim st As String, msg As String
    Dim i As Long, CH As String

    st = ActiveCell.Text
    msg = Len(st)
    For i = 1 To Len(st)
        CH = Mid(st, i, 1)
        msg = msg & vbCrLf & CH & vbTab & Asc(CH)
    Next i
    MsgBox msg
End Sub

要查看查找带有双引号的示例,请从一个空的工作表开始并运行:

1
2
3
4
5
6
7
8
9
10
11
12
Sub EightInchNails()
    Dim DQ As String, WhereIsIt As Range
    DQ = Chr(34)
    Range("A15").Value ="8" & DQ

    Set WhereIsIt = Range("A:A").Find(what:="8" & DQ, after:=Range("A1"), LookIn:=xlValues, LookAt:=xlPart)

    If WhereIsIt Is Nothing Then
    Else
        MsgBox WhereIsIt.Address(0, 0)
    End If
End Sub


1
range.find"8"""

应该做到的。末尾的前两个引号转义实际的"字符,而第三个引号终止该字符串。