如何修剪Excel VBA中的文本?

问题描述 投票:-1回答:5

我想修剪一个具有这种结构的文本;

base_text = Surname, Name (ID)

desired_text = Name

你能帮帮我,我怎么能这样做?

问候

excel excel-vba vba
5个回答
0
投票

像这样的东西:

Option Explicit
Sub MyAnswer()
    Dim oCell As Range
    For Each oCell In Range("A1:A100")
        If oCell <> "" Then
            If InStr(1, oCell, ", ") <> 0 Then
                If InStr(1, oCell, " (") <> 0 Then
                    oCell = Right(oCell, Len(oCell) - InStr(1, oCell, ",") - 1)
                    oCell = Left(oCell, InStr(1, oCell, " (") - 1)
                End If
            End If
        End If
    Next
End Sub

在这里,我们循环遍历A1:A100范围内的每个单元格。 LeftRight返回给定字符串中符号的数量。 InStr返回当前字符串中符号的位置。 Len返回给定字符串中的符号数。


1
投票
  1. 文字功能,如左,右,中
  2. split函数,其中“”(空格)或“,”是分隔符

0
投票

作为一个公式你可以使用这个,假设Base_textA1

=LEFT(RIGHT(A1,LEN(A1)-FIND(",",A1)),FIND("(",RIGHT(A1,LEN(A1)-FIND(",",A1)))-1)


0
投票

这可以使用正则表达式轻松解决。这将在原始数据旁边的单元格中输出“名称”。它也可以很容易地被操作以获得字符串的所有文本部分。该范围需要更新以匹配您的范围

Sub test()
    Dim rng As Range
    Dim c

    ' Update this line with your Range
    Set rng = Sheet2.Cells(1, 1)

    With CreateObject("VBScript.RegExp")
        .Global = True
        .ignorecase = True
        .Pattern = "[a-z]+"

        For Each c In rng
            If .test(c.Value2) Then
                c.Offset(0, 1).Value2 = .Execute(c.Value2)(1)
            End If
        Next c
    End With
End Sub

0
投票

使用拆分功能

(见:https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/split-function

使用Split函数,您可以根据给定的分隔符将字符串拆分为子字符串。结果是基于零的1-dim子串数组,其项目可以通过其索引号引用。

i)所以你将使用索引1得到第二个子串:

sName = split(base_text, ",")(1)

ii)由于您只想提取名称而不是括号中的id,您必须对此结果执行另一个拆分,现在索引第一个子串(索引0)并通过Trim函数删除空格:

  sName = Trim(Split(sName, "(")(0))

Option Explicit
Sub GetNameToken()
  Dim base_text As String
  Dim sName     As String
' base_text = Application.UserName      ' << actual code
  base_text = "Surname, Name (ID)"      ' << pattern example

' i) get substring right of the colon delimiter (index 1)
  sName = Split(base_text & ",", ",")(1)
' ii) get substring left of the bracket delimiter (index 0)
  sName = Trim(Split(sName & " ", "(")(0))

  MsgBox "UserName = """ & base_text & """" & vbNewLine & _
         "=> """ & sName & """"
End Sub

笔记

i)为了避免在基本文本与其他分隔符的情况下可能的索引乱序错误,我使用了一个技巧:我将一个虚构的冒号分隔符连接到要拆分的文本(这将导致一个空的第二个子串,如果原文中没有冒号分隔符):

sName = Split(base_text & ",", ",")(1)

ii)在第二次拆分中,只有在sName =“”的情况下才需要额外的字符串连接,否则你会尝试拆分一个空字符串。

附加提示

您可以通过UBound函数获取生成的拆分数组项的上部索引,例如n = UBound(Split("one two three"," ")),在这个例子中2(=三个项目索引0,1,2)。

© www.soinside.com 2019 - 2024. All rights reserved.