将单个单元格数组结果转换为单个连续字符串

时间:2018-01-12 16:24:56

标签: string excel-vba join concatenation vba

您好我正在开发一个项目,使用VBSCRIPT_RegExp_1将正则表达式引入Excel。我正在使用下面的vba代码。

Function RegExGet(aString As String, myExpression As String) As Variant             
    Dim RegEx As New VBScript_RegExp_10.RegExp
    Dim newArray() As String                                                            

    RegEx.Pattern = myExpression                                                        
    RegEx.IgnoreCase = True                                                             
    RegEx.Global = True                                                                 
    Set Matches = RegEx.Execute(aString)                                                

    x = Matches.Count                                                                   
    ReDim newArray(x - 1) As String                                                                                                                                      
    cnt = 0

       For Each Match In Matches                                                        
         newArray(cnt) = Match.Value                                                            
         cnt = cnt + 1                                                               
       Next                                                                            

    RegExGet = newArray()
End Function

代码的问题在于,如果返回多个结果,则只显示第一个结果。它将创建一个1乘1的数组,其中除了第一个之外的任何其他结果都被隐藏。瓦时

我希望的是一个修改,以便生成的数组,无论大小如何,都可以将所有结果与&#34 ;;"连接起来。它们之间。即#1; 1; 2; 3;&#34 ;.关于如何使用JOIN或CONCATENATE的任何提示都是最受欢迎的!

谢谢,祝你有愉快的一天!

1 个答案:

答案 0 :(得分:1)

你真的只需要将Join添加到最后一行。

Function RegExGet(aString As String, myExpression As String) As String
    Dim RegEx As New VBScript_RegExp_10.RegExp
    Dim newArray() As String
    Dim x As Long, cnt As Long
    Dim Matches As Object, Match As Object

    RegEx.Pattern = myExpression
    RegEx.IgnoreCase = True
    RegEx.Global = True
    Set Matches = RegEx.Execute(aString)

    x = Matches.Count
    ReDim newArray(x - 1) As String
    cnt = 0

       For Each Match In Matches
         newArray(cnt) = Match.Value
         cnt = cnt + 1
       Next

    RegExGet = Join(newArray(), ";")
End Function

'example
Sub y()

MsgBox RegExGet("123456789", "\d")

End Sub