VBA 在选定行的单元格上查找特定关键字和存储公式
VBA Find specific keywords and store formula on cells of selected rows
我在 table 中得到了以下数据,我的要求是照顾单词 Plan/Actual Input DOC Qty
、Actual Daily Mortality
、Forecast Qty
,它出现了很多次,并且我要在他们行的每个单元格中存储一个公式。
我得到了以下代码,但我不太确定这是否正确,因为我在上面遇到了很多错误。如果我错了,请看一下并纠正我。任何帮助将不胜感激。
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
您可以尝试另一种搜索特定关键字的方法。
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 是一个可以从字符串中搜索子字符串的函数。
我在 table 中得到了以下数据,我的要求是照顾单词 Plan/Actual Input DOC Qty
、Actual Daily Mortality
、Forecast Qty
,它出现了很多次,并且我要在他们行的每个单元格中存储一个公式。
我得到了以下代码,但我不太确定这是否正确,因为我在上面遇到了很多错误。如果我错了,请看一下并纠正我。任何帮助将不胜感激。
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
您可以尝试另一种搜索特定关键字的方法。
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 是一个可以从字符串中搜索子字符串的函数。