VBA在所选行的单元格上查找特定关键字并存储公式

时间:2015-07-20 12:45:09

标签: vba excel-vba excel-2010 worksheet-function excel

我在表格中收到了以下数据,我的要求是照看Plan/Actual Input DOC QtyActual Daily MortalityForecast Qty这个词很多,并且我要去存储在他们的行的每个单元格中的公式
My Table

我得到了以下代码,我不太确定这是否是正确的,因为我有很多错误。如果我错了,请看看并纠正我。任何帮助将不胜感激。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim forecastQty As String
Dim Rng As Range


With Rows("1:1")
forecastQty = Criteria1:=Array("Plan/Actual Input DOC Qty","Actual Daily Mortality","Forecast Qty")
  Set Rng = .Find(what:=forecastQty, _
  after:=.Cells(.Cells.Count), _
  LookIn:=xlFormulas, _
  lookat:=xlWhole, _
  SearchOrder:=xlByColumn, _
  SearchDirection:=xlNext, MatchCase:=False)

If Not Rng Is Nothing Then
  ActiveCell.Address.Select
Else
MsgBox "Nothing found"
End If

End With
End Sub

1 个答案:

答案 0 :(得分:0)

您可以尝试另一种搜索特定关键字的方式。

Dim i As Integer
Dim x As String, y As String, z As String, PO As String


i = 2
Do Until Sheets("your sheet name").Cells(i, 1) = ""

x = "Plan"
y = "Actual"
z = "Forecast"

PO = Sheets("your sheet name").Cells(i, 4)

    If InStr(1, PO, x, 1) > 0 Then

        'Do what you want

    ElseIf InStr(1, PO, y, 1) > 0 Then

        'Do what you want

    ElseIf InStr(1, PO, z, 1) > 0 Then

    'Do what you want

    End If

i = i + 1
Loop

这将遍历数据并搜索特定关键字。在你的情况下;

Plan/Actual Input = Plan
Actual Daily Mortality = Actual
Forecast Qty = Forecast

代码将搜索D列的行是否包含特定关键字,您可以将公式放在if else块上。请注意, INSTR 是一个可以从字符串中搜索子字符串的函数。