Excel VBA:如何解决索引和匹配函数类型不匹配错误

时间:2016-07-12 13:50:44

标签: excel vba excel-vba indexing match

当日期计数器发生变化时,我在索引和匹配函数中遇到错误。当我面对错误时,我写了一条评论。如果需要,我上传了我的数据样本。 示例: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

当日期变为1/2/2008时,我面临错误,我该如何解决?!

谢谢

1 个答案:

答案 0 :(得分:2)

由于您使用的是Application.MatchVariant数据类型,因此在调用.Match期间错误不会引发,但col和{{1}等变量如果在搜索范围/数组中找不到该值,则将包含rw类型。

Error值在尝试将其分配给Error数组TypeMismatch时会导致String错误。

所以,你已经到了一半,你只需要处理错误:

aname()

或者,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 似乎是错误的来源,,这里完全不需要,因为:

IndexIndex(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 ROW 号码,rw COLUMN 号码。