【问题标题】:VBA_String cannot be added into array(Error: Expected array)VBA_String 无法添加到数组中(错误:预期数组)
【发布时间】:2016-05-31 12:05:15
【问题描述】:

下午好,

我想在数组中添加一个长字符串,例如“OA_OB_OC_OD_n1”。然后使用 Split 函数将其分成几个部分,并将它们放入我的工作表中,例如: OA|OB|OC|OD|n1|

这是我的代码(所有的 Dim 都已完成):

Public Sub Boutton_Importer_Click()

list_de_controle = "TEXT;" & listPath
Open listPath For Input As #1  
'to read a list which contains the name of files I want to open

Do While Not EOF(1)
    Line Input #1, nom_de_Fich  'read the name of file
    WrdArray() = Split(nom_de_Fich, "_")  'here is the problem

    For Each wrd In WrdArray()
        ActiveCell.Value = wrd
        ActiveCell.Offset(0, 1).Select
    Next wrd

    Open nom_de_Fich For Input As #2  'open the file
    Insérer_contenu  'I have a function here to read the contents
    Close #2

    ActiveCell.Offset(1, 0).Select
    ActiveCell.End(xlToLeft).Select
Loop
Close #1

结束子

如果我改变这部分:

Line Input #1, nom_de_Fich  'read the name of file
WrdArray() = Split(nom_de_Fich, "_")  'here is the problem

For Each wrd In WrdArray()
    ActiveCell.Value = wrd
    ActiveCell.Offset(0, 1).Select
Next wrd

进入:

Line Input #1, nom_de_Fich  'read the name of file
ActiveCell.Value = nom_de_Fich
ActiveCell.Offset(0, 1).Select

效果很好。所以我不知道如何解决这个问题。 提前谢谢!

【问题讨论】:

  • 您收到什么错误信息?虽然我通常不会在使用数组时写()(仅在维度上),但我写了一个快速测试用例,使用你的语法它不会失败。
  • 抱歉耽搁了。错误是预期的数组。我认为这意味着数组仍然是空的?
  • 我写了一个较小的,在下面的评论中。如果可以,请检查一下。

标签: arrays excel vba


【解决方案1】:

好吧,我相信我什么都没做,只是删除所有内容并重新编写所有内容,它可以工作。 毕竟谢谢你!祝你有美好的一天!

【讨论】:

    【解决方案2】:

    我写了一个小一点的,读起来更简单:

    Sub try()
    
        Dim longstr As String
        Dim myarray() As String
        Dim wrd As Variant
    
        longstr = "OA_OB_OC_OD_OE_OF_OG"
    
    
        myarray() = Split(longstr, "_")
        For Each wrd In myarray
            ActiveCell.Value = wrd
            ActiveCell.Offset(0, 1).Select
        Next
    End Sub
    

    再次感谢。

    【讨论】:

    • 这个sn-p是否也应该抛出“expected array”错误?刚刚在 Excel 2013 中运行它并运行良好......
    • 我已经删除了所有内容并再次写入,它起作用了……我很困惑,但它终于起作用了。毕竟谢谢你!
    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多