【问题标题】:Match whole word/phrase and replace匹配整个单词/短语并替换
【发布时间】:2013-05-12 01:57:43
【问题描述】:

我正在尝试用另一个字符串替换一个字符串,但问题是该字符串部分匹配其他字符串。

我正在尝试创建一个函数来搜索另一个电子表格中的每一行,并在找到我的搜索短语时返回该行。当与较长的单词或独特的单词一起使用时,脚本的效果非常好,或者我输入代码短语作为搜索条件。问题是,如果字符串部分匹配其他字符串,它会被复制,我会得到很多错误的结果。

我需要该函数停止在单词中查找结果,而是将单词或短语作为一个整体进行匹配。

到目前为止,这是我的脚本:

Sub Light()
  Dim rng1 As Range
  Dim fnd1 As String
  fnd1 = "Quantity"

  Sheets("TEST").Activate
  Set rng1 = Sheets("TEST").Cells.Find(fnd1)
  If Not rng1 Is Nothing Then
    Range(Cells(rng1.Row, rng1.Column), Cells(Rows.Count, rng1.Column).End(xlUp)).Copy _
      Sheets("TEMPLATE").Range("A5")
    Cells(1, 1).Select
  End If

这里我有我的问题,因为第二个搜索条件部分满足并被复制。

  Dim rng2 As Range
  Dim fnd2 As String
  fnd2 = "Quantity order min"
  Sheets("TEST").Activate
  Set rng2 = Sheets("TEST").Cells.Find(fnd2)
  If Not rng2 Is Nothing Then
    Range(Cells(rng2.Row, rng2.Column), Cells(Rows.Count, rng2.Column).End(xlUp)).Copy _
      Sheets("TEMPLATE").Range("C5")
    Cells(1, 1).Select
  End If

【问题讨论】:

  • 部分......像“菠萝”中的“苹果”?
  • 是的,类似的。如您所见,搜索在两种情况下都包含单词“Quantity”,因此当它找到第一个单词 Quantity 时,它不会查看整个短语。

标签: vba excel match word


【解决方案1】:

肯定会有更好的答案,这甚至可能无法达到您想要的结果 - 但到目前为止还没有其他任何东西!:

Sub Light()
Dim rng1 As Range
Dim fnd1 As String
Dim rng2 As Range
Dim fnd2 As String

fnd1 = "Quantity"
fnd2 = "Quantity order min"

Sheets("TEST").Activate
Set rng1 = Sheets("TEST").Cells.Find(fnd1)
If Not rng1 Is Nothing Then
If Sheets("TEST").Cells.Find(fnd1, LookIn:=xlValues, lookat:=xlWhole) > 1 Then
   Sheets("TEMPLATE").Select
Range("A5").Select
ActiveCell.FormulaR1C1 = fnd1
End If
End If
Sheets("TEST").Activate
Set rng2 = Sheets("TEST").Cells.Find(fnd2)
If Not rng2 Is Nothing Then
If Sheets("TEST").Cells.Find(fnd2, LookIn:=xlValues, lookat:=xlWhole) > 1 Then
   Sheets("TEMPLATE").Select
Range("C5").Select
ActiveCell.FormulaR1C1 = fnd2
End If
End If
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多