我试图创建一个“ If语句”,在其中检查列B是否包含部分字符串(“ BMC-”)。然后在E列中写“物料清单”。
我已经尝试过使用公式,但是我希望将其编写为宏。
= IF(ISNUMBER(SEARCH(“ BMC-”,B14)),“物料清单”,“”)
Sub Descriptions()
For r = 14 To Cells(Rows.Count, "B").End(xlUp).Row ' From row 1 to
the last row with data
On Error Resume Next
If Cells(r, "B") = "BMC-9" > 0 Then
Cells(r, "E").Value = "Bill of Materials"
End If
Next
End Sub
我希望代码循环到最后一行,以在B列中查找包含部分文本“ BMC-”的所有字符串,以在E列中编写“物料清单”
答案 0 :(得分:1)
只需使用您已有的公式,无需循环。还声明您的变量。利用变量代替对常数值进行硬编码,从而使代码更易于调整和维护。这样的事情应该适合您:
Sub tgr()
'Declare variables
Dim ws As Worksheet
Dim lHeaderRow As Long
Dim sSearchCol As String
Dim sOutputCol As String
Dim sTextToFind As String
Dim sTextToWrite As String
'Set this to the actual worksheet where you want the formula
Set ws = ActiveWorkbook.ActiveSheet
'Define variables
lHeaderRow = 13 'Header Row. Actual data and results will start on the next row
sSearchCol = "B" 'Column to search for the text
sOutputCol = "E" 'Column to output results
sTextToFind = "BMC-" 'Text to search for
sTextToWrite = "Bill of Material" 'Text that will be output when search text is found
'Use previously defined variables to establish range
With ws.Range(sOutputCol & lHeaderRow + 1 & ":" & sOutputCol & ws.Cells(ws.Rows.Count, sSearchCol).End(xlUp).Row)
If .Row <= lHeaderRow Then Exit Sub 'No data
'Apply your formula to all rows in the range at once
.Formula = "=IF(ISNUMBER(SEARCH(""" & sTextToFind & """," & sSearchCol & .Row & ")), """ & sTextToWrite & """, """")"
'Convert cells to values
.Value = .Value
End With
End Sub
答案 1 :(得分:0)
尽管我倾向于使用InStr(),Tim的情况很Like
:
Sub Descriptions()
For r = 14 To Cells(Rows.Count, "B").End(xlUp).Row
'On Error Resume Next 'get rid of that... find error and fix/build logic, don't ignore it
If Instr(Cells(r, "B").Value, "BMC-9") Then
Cells(r, "E").Value = "Bill of Materials"
End If
Next
End Sub
答案 2 :(得分:0)
您可以使用 split()函数尝试这种方法:
Sub NewCode()
For r = 14 To Cells(Rows.Count, "B").End(xlUp).Row
Dim myArray As Variant
myArray = Split(Cells(r, "B"), "BMC-")
If UBound(myArray) > 0 Then
Cells(r, "E").Value = "Bill of Material"
End If
Next r
End Sub