帖子已在原始帖子下方更新
我正在使用两个表并希望将它们连接起来,但是,第一部分包含的值比第二部分多。我能够通过在Evaluate
函数中添加一个IfError
来解决这个问题,从代码示例 (1( 到 (2( 可以看出(使用来自 If 错误然后空白的帮助(
(1(
Worksheets("Sheet1").Range("Cell1").Value = Worksheets("Sheet1").Evaluate("=INDEX(data,MATCH(value,lookup_column,FALSE),column)")
(二(
Worksheets("Sheet1").Range("Cell1").Value = Worksheets("Sheet1").Evaluate("=INDEX(data,MATCH(value,lookup_column,FALSE),column), Cell2")
但是,我仍然想要一条消息,说有一个错误,所以我尝试了
Sub Name()
Application.ScreenUpdating = False
On Error GoTo Msg
Worksheets("Sheet1").Range("Cell1").Value = Worksheets("Sheet1").Evaluate("=INDEX(data,MATCH(value,lookup_column,FALSE),column), Cell2")
Worksheets("Sheet1").Range("Cell1").Value = Worksheets("Sheet1").Evaluate("=INDEX(data,MATCH(value,lookup_column,FALSE),column)")
Exit Sub
Msg: MsgBox "You've had a fatal error"
End
End Sub
它没有返回消息,我假设这是因为 VBA 的代码编写正确,并且是 Excel 函数代码出错。那么有没有办法使用另一个函数来确定 excel 错误呢?
这是较大编码的子部分,所以我知道它可以在 excel 中单独完成,但这只是整体的一小部分。提前谢谢。
UDATE:
通过注释,我能够删除评估函数并将原始代码替换为以下内容:
Sub SetWaterfall ()
Application.ScreenUpdating = False
Dim vMatchVal As Variant
If Not IsError(vMatchVal) Then
vMatchVal = Application.Match(Sheets("Sheet1").Range("SelectLine"), Sheets("Sheet1").Range("AS8:AS34"), 0)
Worksheets("Sheet1").Range("AW45").Value = Application.Index(Sheets("Controls").Range("AR8:AR34"), vMatchVal)
Else
Worksheets("Controls").Range("AW45").Value = "Not Data"
MsgBox "First number not found"
End If
End Sub
问题仍然是索引/匹配函数返回#NA
错误,并且消息框永远不会出现。
(帮助将索引/匹配功能从Excel公式转换为VBA代码 https://www.mrexcel.com/forum/excel-questions/691904-translate-index-match-function-vba-code.html(
(如果此编辑过程不是让我知道的正确程序,我将关闭帖子(
在修改后的代码中,在对要测试错误的变量进行赋值之前,您有If Not IsError
测试!
让我们解决这个问题,并尝试其他一些重构(为了易读性(。如果这仍然无法按预期工作,您将需要提供一些示例数据,其他人可以使用这些数据来复制错误。
Sub SetWaterfall()
' It's not necessary to disable ScreenUpdating for this procedure...
' Application.ScreenUpdating = False
Dim theSheet as Worksheet, controls as Worksheet
Dim vMatchVal As Variant
Dim lookupVal as String
Dim matchRange as Range, indexRange as Range
Set theSheet = Sheets("Sheet1")
Set controls = Sheets("Controls")
Set matchRange = theSheet.Range("AS8:AS34")
Set indexRange = controls.Range("AR8:AR34")
lookupValue = theSheet.Range("SelectLine").Value
vMatchVal = Application.Match(lookupVal, matchRange, 0)
If Not IsError(vMatchVal) Then
theSheet.Range("AW45").Value = Application.Index(indexRange, vMatchVal)
Else
controls.Range("AW45").Value = "Not Data"
MsgBox "First number not found"
End If
End Sub