【问题标题】:Can you use split-function recursively on an split-item in VBA?您可以在 VBA 中的拆分项上递归使用拆分功能吗?
【发布时间】:2020-11-06 00:13:19
【问题描述】:

我正在努力解决 VBA 中的拆分功能。尽管我尝试使用Dim as VariantDim as String 切换,但也许我的声明有问题。

我的代码如下:

'Split the txtString variable at every "|" and add every split string item to an array split_sText
Dim txtString as String
.
.
.
Dim split_sText() As String
split_sText() = Split(txtString, "|")

Pick the first part of respective item out of that array and place it at the right cell
Sheets(Table1).Cells(1, 1) = Split(split_sText(15), "_")'

split_sText(15) 看起来像这样:“ABC_1234”。在那个字符串中,我只想得到“ABC”。

由于“运行时错误 13 不匹配类型”,错误发生在最后一行,这很奇怪,因为我已将变量声明为字符串。

感谢您的帮助!

【问题讨论】:

  • Split(split_sText(15), "_") 的结果将是一个包含 2 个元素的数组。如果您只想要ABC 部分,请尝试Sheets(Table1).Cells(1, 1) = Split(split_sText(15), "_")(0)
  • 这确实是一个非常好的观点。我试过你的想法,但不幸的是它不起作用。用字符串 "abc_1234" 替换 split_sText(15) 仍然会触发相同的错误。

标签: excel vba split


【解决方案1】:

我相信您正在寻找错误的地方。

Sheets(Table1) 是错误的来源。

Sheets 对象的 Index 参数必须是数字或工作表名称。 Table1 最有可能是 CodeName。对象的CodeName 返回实际对象。

所以如果Table1 是CodeName,则改为

Table1.Cells(1,1) = ...

如果 Table1 恰好是工作表名称,那么它将是

Sheets("Table1").Cells(1,1) = ...

如果您查看 VBE 中的“项目资源管理器”窗口,您将在项目的 Microsoft Excel 对象下看到一个或多个工作表对象。 CodeName 是工作表的名字;工作表Name 是括号中的名称。

拆分字符串的方式还有其他问题,但您的代码应该使用正确的 Sheets 引用。

【讨论】:

    【解决方案2】:

    Dim Sp() As String 声明了一个字符串类型的数组,其中元素个数未定义。

    Sp = Split("a_b_c_", "_") 将数组分配给已声明的变量,同时定义元素的数量,从 0 开始。

    Debug.Print Sp(2) 将第三个元素打印到即时窗格。

    Cells(1, 1).Value = Sp(2) 将相同的值分配给单元格。

    Split 函数返回一个字符串类型的数组。但是,以下方法也可以使用。

    Dim Sp As Variant
    Sp = Split("a_b_c_", "_")
    Cells(1, 1).Value = Sp(2)
    

    请注意,变量 没有 声明为数组,因为变量 c 本质上可以是任何东西。 Dim Sp() As Variant 将导致 Sp = Split("a_b_c_", "_") 失败。

    作为最后一个转折点,您还可以通过下面的代码避免使用Sp

    Cells(1, 1).Value = Split("a_b_c_", "_")(2)
    

    【讨论】:

      【解决方案3】:

      split_sText(15) 看起来像这样:“ABC_1234”。在那个字符串中,我只想得到“ABC”。

      如果有一个低于分数,那么会有一个包含两项的数组,并且您只能将一个数组项分配给一个单元格:

      Dim split_sText() As String
      split_sText() = Split(txtString, "|")
      
      Dim split_sTextNested() As String
      split_sTextNested = Split(split_sText(15), "_")
      
      Sheets(Table1).Cells(1, 1) = split_sTextNested(0)
      

      【讨论】:

        猜你喜欢
        • 2016-02-26
        • 1970-01-01
        • 2018-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        相关资源
        最近更新 更多