删除 || (管道)在列内文本的末尾

Ulq*_*fer 4 excel vba

我有这个问题,我似乎无法解决...

在 LI 列中有一些角色,这些角色被 || 划分 (管道)。

问题:有些人像这样提供他们想要使用的这些角色:

Testing||Admin||Moderator||
Run Code Online (Sandbox Code Playgroud)

但这对我们用来导入这些角色的脚本不起作用,我希望看到的是,每当 || (pipes) 被使用,并且在使用管道之后,如果后面没有任何文本,它应该删除最后的管道。

我尝试的是查找和替换选项,但这也会删除文本之间的管道。

希望可以有人帮帮我!

问题:

Testing||Admin||Moderator||
Run Code Online (Sandbox Code Playgroud)

解决方案:

Testing||Admin||Moderator
Run Code Online (Sandbox Code Playgroud)

Sid*_*out 7

A simple formula can solve your requirements

=IF(RIGHT(TRIM(A1),2)="||",LEFT(TRIM(A1),LEN(TRIM(A1))-2),A1)
Run Code Online (Sandbox Code Playgroud)

The above formula is based on the below logic.

  1. Check if the right 2 characters are ||
  2. If "Yes", then take the left characters (LEN - 2)
  3. If "No", then return the string as it is.

在此处输入图片说明

如果您仍然需要 VBA,请尝试使用此代码一次性更改整个列。此处给出了有关此方法的说明。

出于演示的目的,我假设数据是在列ASheet1。根据情况更改。

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lrow As Long
    Dim rng As Range
    Dim sAddr As String
    
    Set ws = Sheet1
    
    With ws
        lrow = .Range("A" & .Rows.Count).End(xlUp).Row
        
        Set rng = .Range("A1:A" & lrow)
        sAddr = rng.Address
        
        rng = Evaluate("index(IF(RIGHT(TRIM(" & sAddr & _
                              "),2)=""||"",LEFT(TRIM(" & sAddr & _
                              "),LEN(TRIM(" & sAddr & _
                              "))-2)," & sAddr & _
                              "),)")
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

在行动

我只将工作表的名称和范围更改为 L 和 L2:L。– 乌尔奇奥拉·希弗 17 分钟前

在此处输入图片说明


bra*_*raX 5

有不同的方法可以做到这一点,但这里是一种:

Function FixPipes(val As String) As String
    Dim v As Variant
    
    v = Split(val, "||")
    If Len(v(UBound(v))) > 0 Then
      FixPipes = val
    Else
      FixPipes = Mid$(val, 1, Len(val) - 2)
    End If
End Function
Run Code Online (Sandbox Code Playgroud)

这是另一种方法:

Function FixPipes(val As String) As String
    If Mid$(val, Len(val) - 1, 2) <> "||" Then
      FixPipes = val
    Else
      FixPipes = Mid$(val, 1, Len(val) - 2)
    End If
End Function
Run Code Online (Sandbox Code Playgroud)

用法:

Sub test()
    Debug.Print FixPipes("Testing||Admin||Moderator||")
End Sub
Run Code Online (Sandbox Code Playgroud)

或者:

Sub LoopIt()
    ' remove this line after verifying the sheet name
    MsgBox ActiveSheet.Name

    Dim lIndex As Long
    Dim lastRow As Long
    lastRow = Range("L" & Rows.Count).End(xlUp).Row
    
    For lIndex = 1 To lastRow
      Range("L" & lIndex) = FixPipes(Range("L" & lIndex))
    Next
End Sub
Run Code Online (Sandbox Code Playgroud)

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/split-function

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/mid-function