将多个单元拆分为列

时间:2016-03-09 15:05:11

标签: excel excel-vba vba

我有多个像

这样的字符串的单元格

有关。 ex cel A1

m2_10cm[0.10],m2_20cm[0.20],m2_5cm[0.05],m3[1.9]

和单元格A2

m3_22[2.2],m3_19[1.9]

我可以将它拆分为一列,如

  Column  B
    Cell 1   m2_10cm[0.10]
    Cell 2 m2_20cm[0.20]
    Cell 3 m2_5cm[0.05]
    Cell 4 m3[1.9]
    Cell 5 m3_22[2.2]
    Cell 6 m3_19[1.9]

我将为任何帮助提供帮助

2 个答案:

答案 0 :(得分:0)

这是一个解决方案,您需要隐藏所有其他列: 假设你有A1中的值,然后输入以下公式:

B1: =IF(ISERR(FIND(",";A1;1));A1;LEFT(A1;FIND(",";A1;1)-1))
C1: =IF(ISERR(FIND(",";A1;1));"";RIGHT(A1;LEN(A1)-FIND(",";A1;1)))
然后

B1将包含列表中的第一个值,C1将包含列表减去第一个值。现在您可以将这些公式复制到D1和E1,它们现在看起来像

D1: =IF(ISERR(FIND(",";C1;1));C1;LEFT(C1;FIND(",";C1;1)-1))
E1: =IF(ISERR(FIND(",";C1;1));"";RIGHT(C1;LEN(C1)-FIND(",";C1;1)))

现在继续根据需要将此公式复制到右侧。

完成此操作后,您可以隐藏包含缩短列表的所有列,从C开始,然后是E,等等。

答案 1 :(得分:0)

在Excel中使用VBA代码:

注意:google如何在工作表上输入命令按钮并将其粘贴为代码。

Option Explicit

' note: vbNullString is the same as "" (empty string)

Const START_ROW = 1
Const SRC_COL = 1    ' column A
Const DST_COL = 2    ' column B

' this gets triggered when the button is pressed
Private Sub CommandButton1_Click()
    ' call the routine
    Call Go
End Sub

Function Go()
    ' assume the button is on the sheet to be processed
    Dim ws As Excel.Worksheet
    Set ws = Excel.ActiveSheet

    Dim srcRow As Integer ' current row being processed
    Dim dstRow As Integer ' current row to put result in
    srcRow = START_ROW: dstRow = START_ROW

    ' keep going while column 'A' is not blank
    While ws.Cells(srcRow, SRC_COL) <> vbNullString
        Call Split(ws, ws.Cells(srcRow, SRC_COL), dstRow)
        srcRow = srcRow + 1
    Wend
End Function

Sub Split(ws As Excel.Worksheet, srcStr As String, ByRef dstRow As Integer)
    If (srcStr = vbNullString) Then
        'remove comment if you want blanks at the end
        ' ex. Apple,Banana, 
        '     will create 3 entries, notice the comma at the end 
        'ws.Cells(dstRow, DST_COL) = vbNullString
        'dstRow = dstRow + 1
        Exit Sub
    endif

    ' find ","
    Dim pos As Integer
    pos = InStr(1, srcStr, ",")
    If (pos = 0) Then
        ' no "," - put the whole string
        ws.Cells(dstRow, DST_COL) = Trim(srcStr)
        dstRow = dstRow + 1
    Else
        ' has "," - put the left part of the string
        ' ex: apple,banana,carrot
        '     put "apple"
        '     continue processing "banana,carrot"
        ws.Cells(dstRow, DST_COL) = Trim(Mid(srcStr, 1, pos - 1))
        ' move to next row and process the right of the string
        dstRow = dstRow + 1
        Call Split(ws, Mid(srcStr, pos + 1), dstRow)
    End If
End Sub