使用VBA,如何最后删除addidtional重复字符

时间:2018-05-21 10:22:37

标签: excel vba excel-vba excel-formula

我有多行,我需要在每个单元格值的末尾加上“@#”字符,  我可以添加这些字符,但最后它会打印额外的字符(@#)

我的excel文件:从这个excel文件中,我需要为每个单元格加入@#的值并输入记事本

Excel File for Input

我的输出应该是:(实际和预期)

Actual and Expected Output

这是我的代码:

sub join()
dim LRow as long
dim LCol as long
Dim str1 as string
Dim str2 as string
Dim ws1 As Worksheet
Set ws1 = ActiveWorkbook.Worksheets(1)
 plik = ThisWorkbook.Path & "\" & "BL2ASIS" & ws1.Name & ".txt"
 Open plik For Output As 2
With ws1
LRow = .Cells(.Rows.Count, 1).End(xlUp).Row
LCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
LCol = LCol - 2
slast = vbNullString


str2 = Join(Application.Transpose(Application.Transpose(.Cells(n, "A").Resize(1, 2).Value)), "")
str1 = str2 & Join(Application.Transpose(Application.Transpose(.Cells(n, "C").Resize(1, LCol).Value)), "@#") & "@#"
str1 = Replace(str1, "=", vbNullString)
str1 = Replace(str1, "@#@#", "@#")


Print #2, str1
End with

end sub

3 个答案:

答案 0 :(得分:1)

使用正则表达式替换多个实例。

注意:

  1. 如果只想在字符串末尾替换重复,则将正则表达式模式更改为(@#){2,}$。这将处理2次或更多次。
  2. 如果只担心最后两次出现,请使用(@#)\1$
  3. <强>代码:

    Option Explicit
    
    Sub TEST()
        Dim testString As String, pattern As String
        testString = "xxxxx@#@#"
        testString = RemoveChars(testString)
        Debug.Print testString
    End Sub
    
    Public Function RemoveChars(ByVal inputString As String) As String
    
        Dim regex As Object, tempString As String
        Set regex = CreateObject("VBScript.RegExp")
    
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .pattern = "(@#){2,}"
        End With
    
        If regex.TEST(inputString) Then
            RemoveChars = regex.Replace(inputString, "@#")
        Else
            RemoveChars = inputString
        End If
    
    End Function
    

答案 1 :(得分:1)

你可以替换你的行:

str1 = Replace(str1, "@#@#", "@#")

使用:

Do Until Len(str1) = Len(Replace(str1, "@#@#", "@#"))
    str1 = Replace(str1, "@#@#", "@#")
Loop

将继续应用替换,直到这样做没有意义(即长度不变)

修改

很抱歉更改已接受的答案,但我注意到您可能希望保留@#@#的实例,如果它们出现在行的末尾以外的其他地方。如果你这样做,那么下面会更好,因为它只修剪最右边的字符:

Do Until Right(str1, 4) <> "@#@#"
    str1 = Left(str1, Len(str1) - 2)
Loop

答案 2 :(得分:1)

您获得重复字符的原因是因为您正在加入空数组元素。删除重复分隔符的替代方法是使用UDF仅加入非空值。请参阅下面的功能。

Sub TestJoin()
    Dim r As Range: Set r = Worksheets("Sheet1").Range("B1:B12")
    Dim arr() As Variant
    arr = Application.Transpose(r)
    Debug.Print NonNullJoin(arr, "#") & "#"
End Sub

Function NonNullJoin(SourceArray() As Variant, Optional Delimiter As String = " ") As String
    On Error Resume Next
    Dim i As Long: For i = 0 To UBound(SourceArray)
        If CStr(SourceArray(i)) <> "" Then NonNullJoin = _
            IIf(NonNullJoin <> "", NonNullJoin & Delimiter & CStr(SourceArray(i)), CStr(SourceArray(i)))
    Next i
End Function