当前位置:  开发笔记 > 后端 > 正文

VBA:将Variable Array转换为String

如何解决《VBA:将VariableArray转换为String》经验,为你挑选了2个好方法。

我试图使用vba将变量数组转换为字符串.我尝试了两种方法,但没有它们起作用,它们似乎都在同一点上集中.

    Dim cell As Range
    Dim val As Variant

    For Each cell In Range("packing_list[Code]")
        val = cell.Value
    Next cell

    MsgBox Join(val, "//")

    Dim oSh As Worksheet
    Dim CodeRange As Variant

    Set oSh = ActiveSheet
    CodeRange = oSh.Range("packing_list[Code]").Value

    MsgBox Join(CodeRange , "//")

它们都是MsgBox行上的错误.我做错了什么?

谢谢



1> Branden Keck..:

您尝试加入的值不是字符串数组.Join应该用在数组上

以下是Microsoft指令的链接:https://msdn.microsoft.com/en-us/library/b65z3h4h%28v=vs.90%29.aspx

他们的例子是:

Dim TestItem() As String = {"Pickle", "Pineapple", "Papaya"}
Dim TestShoppingList As String = Join(TestItem, ", ")

您的代码应该类似于:

Dim i As Integer
Dim cell As Range
Dim val() As Variant '() indicate it is an array

i = 0
For Each cell In Range("packing_list[Code]")
    ReDim Preserve val(0 to i) As Variant 'must resize array to fit number of items
    val(i) = cell.Value 'i is the position of the item in the array
    i = i + 1 'increment i to move to next position
Next cell

'Now that you have an array of values (i.e. ("String1", "String2", ...) instead of just "String" you can:

MsgBox Join(val, "//")



2> brettdj..:

Tranpose 可用于为单个列或行生成一维数组或字符串。

所以A1:A10你可以用

MsgBox Join(Application.Transpose([a1:a10]), ",")

连续工作需要一秒钟Transpose,因此A1:K1

MsgBox Join(Application.Transpose(Application.Transpose([a1:k1])), ",")

推荐阅读
雯颜哥_135
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有