Excel文本到行代码错误

时间:2018-08-23 10:55:34

标签: excel vba excel-vba excel-formula

enter image description here

嗨,这里是预期的输入和预期的输出

我正在使用这些代码,但是在第一栏中而不是与输出相同,只是给出了序列号。 enter image description here

Sub SplitByRows()
Dim Col As Long, LastRow As Long, ColParts() As String
LastRow = Cells(Rows.Count, "B").End(xlUp).Row
For Col = 2 To 5 'Column A to Column C
ColParts = Split(Join(Application.Transpose(Range(Cells(2, Col), 
Cells(LastRow, Col))), ","), ",")
With Cells(2, Col).Resize(UBound(ColParts) + 1)
  .NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(@_)"
  .Value = Application.Transpose(ColParts)
End With
Next
End Sub

2 个答案:

答案 0 :(得分:0)

首先,您从B列而不是A列开始:

For Col = 2 To 5 'Column A to Column C

应该是:

For Col = 1 To 5 'Column A to Column C

然后,据我所知,您需要将A列的值设为:

1,1
2,2,2

答案 1 :(得分:0)

这是一个有效的代码:

Option Explicit

Sub SplitByRows()
Dim Col As Long, LastRow As Long, ColParts() As String
Dim i, a, k As Long
Dim StringNo As String
LastRow = Cells(Rows.Count, "B").End(xlUp).Row

For i = 2 To LastRow
    k = CountChrInString(Cells(i, 2).Value, ",")
    StringNo = Cells(i, 1).Value
        For a = 1 To k
            Cells(i, 1).Value = Cells(i, 1).Value & "," & StringNo
        Next a
Next i

For Col = 1 To 5 'Column A to Column C
    ColParts = Split(Join(Application.Transpose(Range(Cells(2, Col), Cells(LastRow, Col))), ","), ",")
    With Cells(2, Col).Resize(UBound(ColParts) + 1)
    .NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(@_)"
    .Value = Application.Transpose(ColParts)
    End With
Next

End Sub


Public Function CountChrInString(Expression As String, Character As String) As Long

    Dim iResult As Long
    Dim sParts() As String

    sParts = Split(Expression, Character)

    iResult = UBound(sParts, 1)

    If (iResult = -1) Then
    iResult = 0
    End If

    CountChrInString = iResult

End Function

我所做的就是在代码的开头以及第一列中添加一些“,”。

为此,我需要在第二列的单元格中计算“,”的数量。   这是通过以下页面中的功能完成的:How to find Number of Occurences of Slash from a strings

之后,您的代码就完成了其余的工作;)