【发布时间】:2020-05-14 10:45:20
【问题描述】:
编辑:当我尝试运行此功能时,我收到 #VALUE! 错误。如果我只做If statement 就可以了,所以逻辑看起来不错。问题是重新创建INDEX MATCH MATCH 公式。我正在尝试引用名为“Headcount”的表的第 15 列,并在“Region”列中找到相应的结果。
tblHeadcount:
Name Region
Bob 001
Jake 003
Bill 001
Function CO_GLREFORM(CellRef1 As Range, CellRef2 As Range, CellRef3 As Range) As String
Dim tblHeadcount As ListObject
Dim matchColResult As Long
Dim matchRowResult As Long
Dim indexResult As Variant
'------THIS IS THE CODE THAT CREATES #VALUE! ERROR
'Set tblHeadcount = ActiveSheet.ListObjects("Headcount")
'matchColResult = WorksheetFunction.Match(CellRef3, tblHeadcount.ListColumns(15).DataBodyRange, 0)
'matchRowResult = WorksheetFunction.Match(tblHeadcount.HeaderRowRange(16), tblHeadcount.TotalsRowRange, 0)
'indexResult = WorksheetFunction.Index(tblHeadcount.DataBodyRange, matchColResult, matchRowResult)
If UCase(CellRef1) = "CONFERENCE" Or UCase(CellRef1) = "TRAINING" Then
'-----THIS IS THE CODE GENERATED (WITH ADJ) FROM THE MACRO RECORDER------
ActiveCell.FormulaR1C1 = _
"=CellRef2 &""-""&INDEX(Headcount,MATCH(CellRef3,Headcount[Name Verification],0),MATCH(Headcount[[#Headers],[Region]],Headcount[#Headers],0))&""-7210.0100"""
'-----THIS IS MY ATTEMPT TO RECREATE THE FORMULA
'CO_GLREFORM = CellRef2 & "-" & indexResult & "-7210.0100"
Else
ActiveCell.FormulaR1C1 = _
"CO_GLREFORM = CellRef2 &""-""&INDEX(Headcount,MATCH(CellRef3,Headcount[Name Verification],0),MATCH(Headcount[[#Headers],[Region]],Headcount[#Headers],0))&""-7210.0105"""
'CO_GLREFORM = CellRef2 & "-" & indexResult & "-7210.0105"
End If
'--------THIS IS THE FORMULATE I AM REPLICATING----------------
'If(OR(CellRef1="CONFERENCE",CellRef1="TRAINING"),CellRef2&"-"& _
INDEX(Headcount,MATCH(CellRef3,Headcount[Name Verification],0), MATCH(Headcount[[#Headers],[Region]],Headcount[#Headers],0))&"-7210.0100",CellRef2&"-"& _
INDEX(Headcount,MATCH(CellRef3,Headcount[Name Verification],0),MATCH(Headcount[[#Headers],[Region]],Headcount[#Headers],0))&"-7210.0105")
End Function
``
【问题讨论】:
-
您在索引上缺少范围标准。
-
顺便说一句,您可以通过使用
if UCase(CellRef1) = "CONFERENCE"来避免 CellRef1 的不同大小写变体的三重检查 -
为什么不将单元格写入工作表网格以进行故障排除并找出问题所在。然后,一旦它工作,将其放入 VBA。
-
@teylyn 谢谢你的 UCase()。我在网上看到了这个,但直到现在才点击。该公式在电子表格中有效,我只是在努力翻译成 VBA。你的意思是做“录制宏”功能吗?