【问题标题】:Excel VBA Subscript Out Of Range on 00:00 SplitExcel VBA 下标在 00:00 拆分时超出范围
【发布时间】:2019-08-14 20:21:59
【问题描述】:

我正在使用 VBA 循环遍历 Excel 中的表,以将值拆分到下一列。表格如下所示。

+---------------------+---------------------+
| Interval Start Date | Interval Start Time |
+---------------------+---------------------+
| 2019-07-01 04:00    |                     |
| 2019-07-01 05:00    |                     |
| 2019-07-01 05:00    |                     |
| 2019-07-01 05:00    |                     |
| 2019-07-01 06:00    |                     |
+---------------------+---------------------+

第一列是A,第二列是B。 我正在使用我编写/获得的这段代码。

Sub SplitCells()
    Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).row).Copy Destination:=Range("B2")
    Dim rLastRow As Range
    Dim row As Integer
    Set ws = Sheets("Monthly Queue activity by hour-")
    row = 2
    Set rLastRow = Cells(Rows.Count, "B").End(xlUp)
    rLastRow = rLastRow - 1

    Dim TestArray As Variant
    With ws
        Do
            TestArray = Split(CStr(.Cells(row, 1).Value))
            .Cells(row, 2) = TestArray(1)
            row = row + 1
        Loop Until row = rLastRow
    End With
End Sub

如果我拆分的时间戳是 00:00,它将给我下标超出范围。我已尝试搜索,但似乎无法找到解决此问题的方法。

我删除带有 00:00 时间戳的条目并且它可以工作,但当它到达末尾时我仍然得到超出范围。

【问题讨论】:

  • 您可以使用.Text 而不是.Value 来检索显示为格式化的内容,但它会更慢。
  • @braX 很好地解决了 00:00 问题。

标签: excel vba


【解决方案1】:

由于 rLastRow 是一个范围,您需要调用 .row 属性来结束循环。这与.Text 的建议应该可以解决问题。

Sub SplitCells()
Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).row).Copy Destination:=Range("B2")
Dim rLastRow As Range
Dim row As Integer
Set ws = Sheets("Monthly Queue activity by hour-")
row = 2
Set rLastRow = Cells(Rows.Count, "B").End(xlUp)
rLastRow = rLastRow - 1

Dim TestArray As Variant
With ws
    Do
        TestArray = Split(CStr(.Cells(row, 1).Text))
        .Cells(row, 2) = TestArray(1)
        row = row + 1
    Loop Until row = rLastRow.row + 1
End With

结束子

【讨论】:

  • 完美,谢谢。我已经盯着这个看了很久了。
  • @Unfundednut 我建议为 Delimiter 函数明确指定 Delimiter 参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 2014-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
相关资源
最近更新 更多