【问题标题】:vba transpose single row to multiple rows in an arrayvba将单行转置为数组中的多行
【发布时间】:2014-11-17 06:08:16
【问题描述】:

我想将逗号分隔值(或任何分隔符)转置为数组中的多行。我看到的大多数示例都保存到 excel 文件中的范围值中。 有没有可以指教的。

strFirstLine:

 row1,row2,row3

数组中的输出,因此我可以在每一行上循环进行操作:

  row1
  row2
  row3

这是我到目前为止的代码。我在 debug.print 部分添加了评论。

line = WorksheetFunction.Transpose(Split(strFirstLine, ","))

ctr = 0
For ctr = LBound(line) To UBound(line)
    Debug.Print LBound(line) --value is 1
    Debug.Print UBound(line) --value is 13
    Debug.Print CStr(line(LBound(line))) --this line fails with "Subscript out of Range" error 
Next ctr

如果您需要更多详细信息,请告诉我。任何想法将不胜感激!

【问题讨论】:

  • 这个不需要 vba,Excel 已经免费提供了
  • 转置?是的,但我需要对数据进行一些操作,因此我想将它保存在一个数组中并访问它。

标签: arrays vba excel split transpose


【解决方案1】:

您可以避免转置功能。只需使用 split 并定义要保存拆分值并完成的行和列值。

检查此代码:

Sub try()
Dim Line() As String
Dim ctr, rw, cl As Integer

strFirstLine = "row1,row2,row3"

Line = Split(strFirstLine, ",")

ctr = 0
rw = 1
cl = 1
For ctr = LBound(Line) To UBound(Line)
    Cells(rw, cl) = Line(ctr)
    rw = rw + 1
Next ctr

End Sub

【讨论】:

    【解决方案2】:

    line这里是一个二维数组,所以使用LBound或UBound时需要指定维度,访​​问值时需要两个索引:

    line = WorksheetFunction.Transpose(Split("row1,row2,row3", ","))
    
    Debug.Print LBound(line, 1), UBound(line, 1) '1,3
    Debug.Print LBound(line, 2), UBound(line, 2) '1,1
    
    
    For ctr = LBound(line, 1) To UBound(line, 1)
        Debug.Print line(ctr, 1)
    Next ctr
    

    【讨论】:

    • 谢谢!!只是出于好奇,是否有理由在二维数组中这样做?这可以在一维数组中完成,如列表或其他东西吗?不过这很好用,再次感谢。
    • 我假设你出于某种原因想要二维数组,但@Paresh J 展示了如何获得一维版本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多