我遇到的问题是存在“类型不匹配”错误,之后“局部窗口”会丢失存储在变量中的值的所有内存。因此,我无法调试问题的来源。
问题发生前的初步代码:
Dim i as Long, j as Long, g as Long
Dim Total_Rows_Help as Long
Total_Rows_Help = Worksheets("Help Worksheet").Range("A" & Rows.Count).End(xlUp).Row
ReDim Min_NDate(2 To Total_Rows_Help, 2 To Total_Rows_Help) As Variant
For i = LBound(Min_NDate, 1) To UBound(Min_NDate, 1)
For j = LBound(Min_NDate, 2) To UBound(Min_NDate, 2)
Min_NDate(i, j) = Worksheets("Help Worksheet").Cells(i, 2) - Worksheets("Help Worksheet").Cells(j, 2)
Next j
Next i
问题出现在这些循环集周围(循环和代码一直工作到它出错的某一点。我相信它是由于Application.Index):
ReDim Count(2 To Total_Rows_Help, 2 To Periods - 1) As Variant
For i = LBound(Min_NDate, 1) To UBound(Min_NDate, 1)
If Application.Large(Application.Index(Min_NDate, i, 0), Periods - 1) < 0 Then
For g = LBound(Count, 2) To UBound(Count, 2)
Count(i, g) = Application.Large(Application.Index(Min_NDate, i, 0), g)
Next g
End If
Next i
下面是附加的excel文件,代码位于Compiled
工作表:
Excel File
奇怪的是,有些时候它不允许调试选项并且只是立即结束。但是,这次调整i值后,我能够得到问题的截图:
它在i
值上崩溃,距离到达循环的上限+1。但是,它应该有效,因为Min_NDate
和Count
的列数与2 To Total_Rows_Help
相同
使用UBound函数设置变量i的上限的相同问题:
答案 0 :(得分:2)
错误是因为您的INDEX
函数未指向您认为的位置。
Index(Min_NDate, i, 0)
将返回索引的ith
行的整行。
但是,Min_NDate数组的LBound为2
。那是阵列的第一行。
所以Index(Min_Ndate,1,0)
实际上会返回Min_Ndate(2,{2-Ubound(Min_NDate,2})
的内容,然后Index(Min_Ndate, Ubound(Min_NDate,1), 0)
将在您的实际数组之外。
您需要调整索引功能中的值。
您的代码中可能存在其他问题。
在调整该条目之后,我发现了另一个实例,其中对Min_NDate
的引用超出了为该数组标注尺寸的方式。
运行以下代码演示了我要编写的内容。在i=9
之后,下一次“运行”将导致Type Mismatch
错误,原因与您的代码相同。
Option Explicit
Sub marine()
Dim v(2 To 10, 2 To 5)
Dim i As Long, j As Long
Dim w
Dim s As String
'Populate the array
For i = 2 To 10
For j = 2 To 5
v(i, j) = i * j
Next j
Next i
'Examine the contents
For i = 2 To 10
'contents of the array
s = ""
For j = 2 To 5
s = s & vbLf & v(i, j)
Next j
s = "Array contents with i = " & i & s & vbLf & vbLf
'Output of the index function with the same arguments
w = "Output of Index Function with i = " & i & vbLf & Join(Application.Index(v, i, 0), vbLf)
MsgBox s & w
Next i
End Sub