首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >部分文本字符串VBA

部分文本字符串VBA
EN

Stack Overflow用户
提问于 2019-04-04 16:33:46
回答 3查看 5.9K关注 0票数 0

我正在尝试创建一个"If语句“,如果它包含一个部分字符串("BMC-"),我将检查B列。然后在E栏中写上“材料清单”。

我已经试过使用公式了,但是我想把它写成宏。

=IF(ISNUMBER(搜索(“BMC-”,B14)),“材料清单”,"")

代码语言:javascript
复制
  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列中写入”物料清单“

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-04-04 16:56:06

尽管我倾向于使用Like (),但提姆有一个坚实的InStr案例:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2019-04-04 17:10:00

只需使用您已经拥有的公式,不需要循环。同时声明变量。使用变量代替硬编码常量值,这样代码就更容易调整和维护。像这样的东西应该对你有用:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2019-04-04 17:20:53

您可以使用split()函数尝试这种方法:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55520989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档