简体   繁体   中英

How to split a string with multiple delimiters and join parts in vba excel?

Good day All,

I would like some input on the following.

I have a function that split parts of a string and converts single digits to double digits. The function uses '.' as a delimiter then joins the parts again by a different delimiter.

When I call the function I simply add "=Outliner(C3)" to the cell I want the formatting to happen.

Everything works beautiful. If I put 14.1.1.1 the function returns 14-01-01-01 which is exactly what I need it to do.

Now a new scenario have come up where I am getting the number as 14.1.1-1 and now the function returns 14-01-01- 43831 which is not what I want. I still want to have 14-01-01-01.

Is there an easy fix to the function. I have added the code below.

Function Outliner(S As String) As String
  Dim x As Long, Parts() As String
  Parts = Split(S, ".")
  For x = 0 To UBound(Parts)
    Parts(x) = Format(Parts(x), "00")
  Next
  Outliner = Join(Parts, "-")
End Function

Replace

Parts = Split(S, ".")

with

Parts = Split(Replace(S, "-", "."), ".")

Since you have also tagged Excel-formula, I'll show you one possibility using native functions available from Excel-2019 onwards:

在此处输入图像描述

Formula in B1 :

=TEXTJOIN("-",,TEXT(FILTERXML("<t><s>"&SUBSTITUTE(SUBSTITUTE(A1,"-","."),".","</s><s>")&"</s></t>","//s"),"00"))

If one has Excel 2019, this would need CSE-entering. With microsoft365 this will be done automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM