如何合并两个String变量

问题描述 投票:0回答:1

我有

Dim FatherContent As String
Dim MotherContent As String

我是VB的新手,我想问一下如何合并2个字符串变量并合并公共名称并删除非常用名称。

vba
1个回答
0
投票

你的问题不是我今天看到的最清楚的问题,但我相信你问的一个方法是,如果你有一个字符串:John DoeJane Doe,你想保留Doe的通用名称。

有几种方法可以做到,但为了简单起见,我们将使用Split()并比较数组:

Option Explicit

Sub test()

    Dim FatherContent As String
    Dim MotherContent As String

    FatherContent = "John Doe"
    MotherContent = "Jane Doe"

    MsgBox getCommonName(FatherContent, MotherContent) '<-- Returns Doe

End Sub

Function getCommonName(ByVal name1 As String, ByVal name2 As String) As String

    Dim name1Arr() As String, name2Arr() As String
    Dim i As Long, x As Long, bFlag As Boolean

    'You should probably add some error handling to ensure the strings
    'passed contain a space so the split() function doesn't fail

    name1Arr = Split(name1)
    name2Arr = Split(name2)

    For i = 0 To UBound(name1Arr)
        For x = 0 To UBound(name2Arr)
            If name1Arr(i) = name2Arr(x) Then
                getCommonName = name1Arr(i)
                bFlag = True
                Exit For
            End If
        Next x
        If bFlag = True Then Exit For
    Next i

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