当日期计数器更改时,我在索引和匹配函数中遇到错误。遇到错误时,我写了一条评论。如果需要,我上传了我的数据样本。范例: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时,我遇到了错误,该如何解决?
谢谢
由于您正在使用Application.Match
和Variant
数据类型,因此在调用时不会出现错误.Match
,但是,如果在搜索范围/数组中找不到该值,则这些变量(例如col
和)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
但是您可能需要在代码中的其他地方进行错误处理,以处理放入数组中的错误值。
我还观察到这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
是一个ROW数,col
是列数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句