【问题标题】:Search cell(s) if it contains any of the strings in array and remove them搜索单元格是否包含数组中的任何字符串并删除它们
【发布时间】:2021-06-24 03:02:08
【问题描述】:

我寻找 VBA 解决方案,但我得到了非 VBA 解决方案和嵌套 Excel 公式解决方案。嵌套公式太多了。

我正在比较一大串文本,例如 FC123ABC2XLBLK
如果它包含数组中的任何字符串,例如 2XL ,请删除 2XL 导致 FC123ABCBLK

这是我目前所拥有的。

Function REMOVESIZE(strInput As String, rngFind As Range) As String

Dim sizeArray() As String
Dim strTemp As String
Dim strFind As String

sizeArray = Split("XS,S,M,L,XL,2XL,3XL,4XL,5XL,6XL,7XL", ",")
strTemp = strInput

For Each cell In rngFind

    If InStr(LCase(strTemp), LCase(sizeArray())) <> 0 Then
        'cell contains size
        strFind = cell.Value
        strTemp = Replace(strTemp, sizeArray(), "")
        
    ElseIf InStr(LCase(strTemp), LCase(sizeArray())) = 0 Then
        'cell DOES NOT contain
        MsgBox "DID NOT WORK! THIS IS JUST FILLER"
    End If
    
Next cell
    
REMOVESIZE = strTemp
    
End Function

尝试将其他人建议但无法理解 VBA 如何比较数组中的字符串的代码和想法拼接在一起。

【问题讨论】:

  • 如果您在多个单元格上循环,这似乎应该是一个子程序而不是一个函数。
  • 您需要为每个输入单元格循环数组sizeArray。此外,您需要确保您的数组元素是根据长度排序的(最长的在前),或者您将(例如)在尝试删除“XL”之前删除“XL”中的“L” , 只剩下“X”

标签: excel vba


【解决方案1】:

作为可以从工作表或其他 VBA 方法调用的 UDF:

Function RemoveSize(strInput As String) As String
    Dim sizeArray() As String, strTemp As String, e
    'make sure items are sorted by length...
    sizeArray = Split("2XL,3XL,4XL,5XL,6XL,7XL,XS,XL,S,M,L", ",")
    strTemp = strInput
    For Each e In sizeArray
        If InStr(strTemp, e) > 0 Then
            RemoveSize = Replace(strTemp, e, "")
            Exit Function 'only 1 replacement required?
        End If
    Next e
    RemoveSize = strTemp
End Function

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 2018-05-05
    • 2018-09-23
    • 2022-08-19
    • 1970-01-01
    • 2018-07-05
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多