如何一次更换多个字符串

时间:2016-02-24 08:15:32

标签: vba word-vba

我反复使用以下代码。有没有更好的选择。

Dim strtxt as string
strtxt = Replace(strtxt, "String1", "")
strtxt = Replace(strtxt, "String2", "")
strtxt = Replace(strtxt, "String3", "")
strtxt = Replace(strtxt, "String4", "")
strtxt = Replace(strtxt, "String5", "")
strtxt = Replace(strtxt, "String6", "")
strtxt = Replace(strtxt, "String7", "")

3 个答案:

答案 0 :(得分:1)

试试这个

Dim mLBound As Long
Dim mUBound As Long
Dim mSize As Long
Dim result As String
Dim RepChars As Variant

RepChars = Array("a", "b", "c")

mLBound = LBound(RepChars)
mUBound = UBound(RepChars)

result = Range("A2").Value

For mSize = mLBound To mUBound
    result = Replace(result, CStr(RepChars(mSize)), "")
Next

Range("A3").Value = result

答案 1 :(得分:1)

或者可以使用正则表达式。示例基于this answer

Option Explicit

Sub ReplaceWithRegex()
    Dim strPattern As String
    Dim strReplace As String
    Dim regEx As Variant
    Dim strtxt As String

    Set regEx = CreateObject("vbscript.regexp")
    strtxt = "String1.String2.String3.String4.String5.String6.String7.String77"
    strPattern = "(String.)" ' (String\d+) for replacing e.g. 'String77' etc.
    strReplace = ""

    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    If regEx.Test(strtxt) Then
        Debug.Print regEx.Replace(strtxt, strReplace)
    Else
        MsgBox ("Not matched")
    End If
End Sub

regexr

答案 2 :(得分:1)

一种方式:

@try
    {
        if((NSNull *)[[responseArray objectAtIndex:indexPath.row] objectForKey:@"banner"] != [NSNull null])
        {
            if([[[responseArray objectAtIndex:indexPath.row] objectForKey:@"banner"] length] > 0)
            {
                NSString *mainBannerimage = [[responseArray objectAtIndex:indexPath.row]objectForKey:@"mainbanner"];
                NSString *bannerImageURL = [NSString stringWithFormat:@"demo.world.com/contest/banners/%@", mainBannerimage];

                NSURL *imageURL = [NSURL URLWithString:bannerImageURL];
                [cell.listBanner sd_setImageWithURL:imageURL
                                   placeholderImage:[UIImage imageNamed:@"profilepic_bg"]];
            }
            else
            {
                //ivUserImage.image = [UIImage imageNamed:@"profilepic_bg"];
            }
        }
    }
    @catch (NSException *exception)
    {

    }
Function RemoveTokens(target As String, ParamArray tokens() As Variant) As String
    Dim i As Long
    For i = 0 To UBound(tokens)
        target = Replace$(target, tokens(i), "")
    Next
    RemoveTokens = target
End Function