Excel VBA:如何解决Index和Match函数types不匹配错误
当date的计数器发生变化时,我遇到索引和匹配函数的错误。 当我面对错误时,我写了一条评论。 如果需要的话,我上传了我的数据样本。 示例: http : //s000.tinyupload.com/?file_id=00243748825638974221
这里是代码:
Sub regionalAverage() Application.ScreenUpdating = False Application.DisplayStatusBar = False Application.EnableEvents = False ActiveSheet.DisplayPageBreaks = False ' *** change the declaration here *** Dim aname() As String Dim rw As Variant Dim col As Variant Dim date_ini As Date Dim date_fin As Date 'create WorkSheet ' *** add Redim here, so the index of the array will start from 1 *** ReDim aname(1 To 2) date_ini = #1/1/2008# date_fin = #1/2/2008# For j = 1 To 3 For conteo = date_ini To date_fin For i = 1 To 2 With Sheets(i) With Application col = .Match(j, Worksheets(i).Range("F2:F23393"), 0) rw = .Match(CLng(conteo), Worksheets(i).Range("D2:D23393"), 0) 'error appeas here aname(i) = .Index(Worksheets(i).Range("H2:H23393"), col, rw) End With End With Next i ' computation area = 6.429571 Sheets("Output").Activate Range("A1").Select ActiveCell.Offset(0, j).Select colname = Split(ActiveCell(1).address(1, 0), "$")(0) Columns("" & colname & ":" & colname & "").Select Selection.Find(What:="", After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Select ActiveCell.Value = "=(SUM(" & aname(1) & "," & aname(2) & "))/" & area & "" Next conteo Next j End Sub
当date改为1/2/2008时,我面对错误,我该如何解决?
谢谢
由于您正在使用Application.Match
和Variant
数据types,因此在调用.Match
期间不会引发错误,但是如果在search范围/数组中找不到该值,那么像col
和rw
这样的variables将包含Error
types。
尝试将其分配给String
数组aname()
时,此Error
值将导致TypeMismatch
错误。
所以,你到了那里,你只需要error handling:
col = .Match(j, Worksheets(i).Range("F2:F23393"), 0) rw = .Match(CLng(conteo), Worksheets(i).Range("D2:D23393"), 0) If Not IsError(col) and Not IsError(rw) Then aname(i) = .Index(Worksheets(i).Range("H2:H23393"), col, rw) Else ' Do something else if there was an error End If
或者, Dim aName() as Variant
,但是你可能需要在你的代码中进一步处理错误值,以处理你input到数组中的错误值。
我也观察到Index
似乎是错误的来源,在这里完全不需要 ,因为:
Index(range_object, row_num, col_num)
与range_object.Cells(row_num, col_num)
所以,我做了:
aname(i) = CStr(Worksheets(i).Range("H2:H23393").Cells(rw, col).Value)
注意:我还假定你最初有rw
和col
在Index
函数的错误位置,而rw
是一个行号, col
是一个列号。