我正试图让VBA评估一个公式,因为它越过一个循环。失败的部分是Evaluate()函数本身,或者至少是我正在使用的语法。
Worksheets("Sheet2").Range("C2").Offset(All, 0) = _
Evaluate("((SUMPRODUCT(SUBTOTAL(2,OFFSET(PercentMet!$I$2,ROW(PercentMet!$I$2:$I$27301)-ROW(PercentMet!$H$2),0)),PercentMet!$I$2:$I$27301,PercentMet!$G$2:$G$27301)/SUMPRODUCT(SUBTOTAL(9,OFFSET(PercentMet!$G$2,ROW(PercentMet!$G$2:$G$27301)-ROW(PercentMet!$G$2),0)),--(PercentMet!$I$2:$I$27301<>""NA""))))")
失败的部分是公式末尾的“”NA“”。使用此公式,每个单元格等于#VALUE!
如果我删除了Evaluate部分,公式可以按我的意愿工作,但我需要评估,因为我循环遍历各种过滤器,每个值都是唯一的。
整个代码如下:
Sub EthFilter()
Application.ScreenUpdating = False
Dim EthName As Range, GradeName As Range, Rate As Variant, Grade As Variant
Dim One As Integer, Zero As Integer, All As Integer
Set EthName = Worksheets("Sheet2").Range("J1")
Set GradeName = Worksheets("Sheet2").Range("K1")
One = 0
All = 0
For Each Raeth In Range("J1:J7")
Zero = 0
Rate = EthName.Offset(One, 0)
With Worksheets("PercentMet")
.AutoFilterMode = False
With .Range("$A$1:$O$27301")
.AutoFilter Field:=6, Criteria1:=Rate
For Each Grades In Range("B2:B9")
Grade = GradeName.Offset(Zero, 0).Value
With Worksheets("PercentMet")
With .Range("$A$1:$O$27301")
.AutoFilter Field:=5, Criteria1:=Grade
Worksheets("Sheet2").Range("C2").Offset(All, 0) = _
Evaluate("((SUMPRODUCT(SUBTOTAL(2,OFFSET(PercentMet!$I$2,ROW(PercentMet!$I$2:$I$27301)-ROW(PercentMet!$H$2),0)),PercentMet!$I$2:$I$27301,PercentMet!$G$2:$G$27301)/SUMPRODUCT(SUBTOTAL(9,OFFSET(PercentMet!$G$2,ROW(PercentMet!$G$2:$G$27301)-ROW(PercentMet!$G$2),0)),--(PercentMet!$I$2:$I$27301<>""NA""))))")
End With
End With
All = All + 1
Zero = Zero + 1
Next Grades
End With
End With
One = One + 1
Next Raeth
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:4)
如果公式的长度是一个问题,那么代替这个(为了清晰起见,添加了换行符):
Worksheets("Sheet2").Range("C2").Offset(All, 0) = Evaluate(
"((SUMPRODUCT(SUBTOTAL(2,OFFSET(PercentMet!$I$2,ROW(PercentMet!$I$2:$I$27301)-
ROW(PercentMet!$H$2),0)),PercentMet!$I$2:$I$27301,PercentMet!$G$2:$G$27301)/
SUMPRODUCT(SUBTOTAL(9,OFFSET(PercentMet!$G$2,ROW(PercentMet!$G$2:$G$27301)-
ROW(PercentMet!$G$2),0)),--(PercentMet!$I$2:$I$27301<>""NA""))))")
您可以使用此表单:
Worksheets("Sheet2").Range("C2").Offset(All, 0) = Worksheets("PercentMet").Evaluate(
"((SUMPRODUCT(SUBTOTAL(2,OFFSET($I$2,ROW($I$2:$I$27301)-
ROW($H$2),0)),$I$2:$I$27301,$G$2:$G$27301)/
SUMPRODUCT(SUBTOTAL(9,OFFSET($G$2,ROW($G$2:$G$27301)-
ROW($G$2),0)),--($I$2:$I$27301<>""NA""))))")
由于所有输入来自同一张纸,您可以使用该纸张的Evaluate
方法,并且将在该纸张的上下文中评估公式。
默认Application.Evaluate
版本使用执行时处于活动状态的工作表。