Batch string concatenation in Excel

后端 未结 12 2114
猫巷女王i
猫巷女王i 2020-12-16 10:31

I have a couple hundred of cells in Excel I would like to concatenate into a single string. Is there a simpler method of doing this than going through them one by one manual

12条回答
  •  长情又很酷
    2020-12-16 11:22

    If your looking for a pure Excel approach (ie no VBA) then the method proposed by James Jenkins is best. If you are happy using VBA then open up the VBA editor, add a new module, and add this code:

    Option Explicit
    
    Public Function JoinText(cells As Variant,Optional delim_str As String) As String
        If cells.Columns.count < cells.Rows.count Then
           JoinText = Join(WorksheetFunction.Transpose(cells), delim_str)
        Else
           JoinText = Join(WorksheetFunction.Transpose(WorksheetFunction.Transpose(cells)), delim_str)
        End If
    End Function
    

    To open the VBA editor easily press Alt-F11. To insert a module you right-click on the workbook listed in the 'Project' window.

    The function is called from excel as follows:

    =JoinText(A1:C1)
    

    If you want to add a delimiter (eg comma):

    =JoinText(A1:C1,",")
    

    The purpose of using the transpose function is to turn the 2d array, 'cells', into a 1d array. The reson for this is that the VBA function Join only accepts a 1d array. The reason for using two of them is if JoinText is looking at a row of cells (which is still just a 2d array) then the first call to transpose, transposes this 2d row array into a 2d column array, the second call turns it into a 1d array.

提交回复
热议问题