分割功能使下标超出范围'循环内部错误

时间:2017-06-06 21:19:32

标签: excel excel-vba for-loop split vba

下面的代码片段试图查看一列单元格的内容。格式化每个单元格:" X.XX _-_ X.XX"。例如:5.66 - 13.44。代码用于获取每个单元格,将每个字符串转换为double,将它们与其他一些数字进行比较,然后重复下一个单元格。

Sub Test()
Dim PC As Worksheet
Dim i As Integer
Dim MaxSpace, MinSpace As Double
Dim MinMax() As String

Set PC = Workbooks("RFQ_Worksheet").Worksheets("Press Choice")

For i = 7 To 52
    MinMax = Split(PC.Cells(i, 8), " - ", 2)
    MaxSpace = CDbl(MinMax(1))
    MinSpace = CDbl(MinMax(0))
    If MaxSpace > 10.3 Then
        'Do some stuff
    End If
Next i

End Sub

包含MaxSpace = CDbl(MinMax(1))的行会使'下标超出范围'错误。但是,当我用PC.Cells(i, 8)替换PC.Cells(7, 8)时,代码运行正常。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

基本上,你在你的循环中击中没有分隔符的单元格。

修正:

Sub Test()
Dim PC As Worksheet
Dim i As Integer
Dim MaxSpace As Double  'you didn't declare it properly
Dim MinSpace As Double
Dim MinMax() As String
Dim r As Range

Set PC = ThisWorkbook.Worksheets("Press Choice")

For i = 7 To 52
    Set r = PC.Cells(i, 8)
    If InStr(r, " - ") <> 0 Then
        MinMax = Split(PC.Cells(i, 8), " - ", 2)
        MaxSpace = CDbl(MinMax(1))
        MinSpace = CDbl(MinMax(0))
        '... etc
    End If
Next i

End Sub