简体   繁体   中英

Excel/VBA - How to insert a character in a string every N characters

I have a report that when exported it displays order numbers (who are always 7 digit long) in a single cell as one single string. Eg: orders 1234567 and 9876543 will appear as 12345679876543 in a single cell. There isn't a maximum number of orders per cell, it varies on every cell.

Is there any way that I can add a character every 7 digits so that I can do a text to columns afterwards?

To avoid using a long and complicated formula, I'd suggest using VBA.

Paste the code below into a standard module and then you can use the formula like this on the worksheet:

=InsertPipe(A1,7)

Function InsertPipe(s As String, interval As Long)
    If interval < 1 Then Exit Function        

    Dim i As Long, result As String

    For i = 1 To Len(s) Step interval
        On Error Resume Next
        result = result & Left(s, interval) & "|"
        s = Mid(s, interval + 1, Len(s) - interval)
    Next i

    InsertPipe = Left(result, Len(result) - 1)
End Function

You could use CONCATENATE .

Ex if values are in two cells: =CONCATENATE(A1,",",B1)

Ex if values are in one cell =IF(LEN(A1)>7,CONCATENATE(LEFT(A1,7),",",MID(A1,8,100)))

EDIT ADD

VBA-Code you could use (found a while ago)

 Sub AddACharacter()

Dim Rng As Range
Dim InputRng As Range, OutRng As Range
Dim Row As Integer
Dim Char As String
Dim Index As Integer
Dim arr As Variant
Dim Val As String
Dim OutVal As String
Dim Num As Integer
xTitleId = "Add a character"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address,Type:=8)
Row = Application.InputBox("Number of characters :", xTitleId, Type:=1)
Char = Application.InputBox("Specify a character :", xTitleId, Type:=2)
Set OutRng = Application.InputBox("Out put to (single cell):", xTitleId, Type:=8)
Set OutRng = OutRng.Range("A1")
Num = 1
For Each Rng In InputRng
Val = Rng.Value
OutVal = ""
For Index = 1 To VBA.Len(Val)
    If Index Mod Row = 0 And Index <> VBA.Len(Val) Then
        OutVal = OutVal + VBA.Mid(Val, Index, 1) + Char
    Else
        OutVal = OutVal + VBA.Mid(Val, Index, 1)
    End If
Next
OutRng.Cells(Num, 1).Value = OutVal
Num = Num + 1
Next
End Sub

You can use a formula copied accross and down, but would be finite in relation to splitting expected, you could use something along these lines, in b1 to z1 in my example.

=MID($A1,IF(COLUMN()-2=0,1,((COLUMN()-2)*7)+1),7)

在此输入图像描述

Assuming the string is in A2, then try this... In B2

=SUBSTITUTE(A2,LEFT(A2,7),LEFT(A2,7)&"|")

The above formula will insert a "|" after seven characters.

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