转置后删除尾随逗号

时间:2014-07-09 09:29:07

标签: excel-vba vba excel

我使用下面的代码来移植数据列,但是,它仍然留下尾随逗号。有人可以帮忙清理它吗?

Sub ReorganizeData()
  Dim X As Long, LastRow As Long, Index As Long
  Dim Sheet As Excel.Worksheet
  Const Interval As Long = 1000

  LastRow = Cells(Rows.Count, "A").End(xlUp).Row

  For X = 1 To LastRow Step Interval
    Index = Index + 1
    Cells(Index, "B") = Application.Trim(Join(Application.Transpose(Cells(X, "A").Resize(Interval).Value), ","))
  Next

  Range("A:A").Delete xlShiftToLeft
End Sub

1 个答案:

答案 0 :(得分:0)

下面将是一个快速修复,但在此过程中实际上会抑制结果字符串中的任何两个连续逗号而不管位置 - 如果这可能有任何问题。尾随逗号是由于加入空单元格,因此可能有一种更好的方法来避免首先填充空单元格

Sub ReorganizeData()
  Dim X As Long, LastRow As Long, Index As Long
  Dim Sheet As Excel.Worksheet
  Const Interval As Long = 1000

  LastRow = Cells(Rows.Count, "A").End(xlUp).Row

  For X = 1 To LastRow Step Interval
    Index = Index + 1
    Cells(Index, "B") = Application.Trim(Join(Application.Transpose(Cells(X, "A").Resize(Interval).Value), ","))
    'Replaces any ",," substring in the above resulting string with an empty string
    Cells(Index, "B") = Replace(Cells(Index, "B"), ",,", "")
    'Cleans up any possible extra single trailing ","
    If Mid(Cells(Index, "B"), Len(Cells(Index, "B")), 1) = "," Then
        Cells(Index, "B") = Left(Cells(Index, "B"), Len(Cells(Index, "B")) - 1)
    End If
  Next

  Range("A:A").Delete xlShiftToLeft
End Sub

编辑:@A Hugues - 你是说在将上述代码用于测试之后,这是你正在观察的内容吗?如果是这样我很困惑,与原始代码相比,添加的额外行仅包括替换任何" ,,"结果字符串中的子字符串,带有空字符串 - +清理任何额外的字符串","在此之后仍然落后。如果确实如此 - 你是否有机会测试替换函数实际上是否按预期工作?

仅供参考我确认这在我的结尾可行。为清晰起见,我还在代码中添加了一些注释

Edit2:也有可能你现在看到的0实际上已经存在于你的原始字符串中,但是在看似很长的一系列traling逗号后被忽视了,如果你能提供确认的话会很棒在这个