1

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

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

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

各种搜索都注意到了这种Chr(34)方法,并且还堆叠了双引号: """"resolves to """""""resolves to""等。我还研究了.find具有特殊转义字符的方法,但也没有成功。

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

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

非常感谢!戴夫

4

3 回答 3

1

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

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

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

要查看使用双引号查找内容的示例,请从空工作表开始并运行:

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
于 2015-05-05T19:57:01.160 回答
1

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

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

...是相同的...

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

...是相同的...

sComparisonText = 8 & """"

...ETC。

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

于 2015-05-05T23:17:25.560 回答
0
range.find "8""" 

应该做的伎俩。最后的前两个引号转义实际"字符,第三个引号终止字符串。

于 2015-05-05T19:51:32.810 回答