我正在尝试使用VBA中的index命令运行宏。它是关于风险矩阵中的风险变量,基于“机会”和“效果”变量。我正在创建一个工具,帮助我的组织进行风险评估。
用户提供机会和效果变量(X和Y轴)的输入。应根据此输入从矩阵中选择总和。 Matrix是在不同的工作表上创建的。
到目前为止,我得到了这个:
Dim ws2 As Worksheet
Set ws2 = Worksheets("RisicoMatrix")
Dim effectIniVar As Long
Dim waarschijnlijkheidIniVar As Long
Dim risicoIniVar As Long
effectIniVar = WorksheetFunction.Match(comboIniEffect, ws2.Range("A3:A10"), 0)
waarschijnlijkheidIniVar = WorksheetFunction.Match(comboIniWaarschijnlijkheid, ws2.Range("B2:I2"), 0)
risicoIniVar = Application.WorksheetFunction.Index(ws2.Range("b3:I10"), effectIniVar, waarschijnlijkheidIniVar)
前两个匹配命令工作正常并给我正确的值,但索引行不起作用。当我运行宏时,我得到运行时错误13,类型不匹配错误,并且在调试时突出显示'索引'行。我知道这条线可能不太正确,但我不明白我在论坛上找到的例子。
我想在VBA中完成此操作,因为这是从表单字段运行的宏。风险矩阵只是其中的一个要素。
非常感谢任何帮助。
提前感谢您的时间和精力。
答案 0 :(得分:0)
我和罗里一起关于返回值并不能隐式转换为Long
类型。
您可以单步执行代码并查看Index(ws2.Range("b3:I10"), effectIniVar, waarschijnlijkheidIniVar)
或者你放置了一个错误处理程序,主要是(我相信)用于调试目的
此外Match()
功能可以有一些" side"效果只要"数字" vs" strings"匹配,可以使用Find()
对象的Range
方法最有效地处理
所以你可以这样:
Option Explicit
Sub main2()
Dim effectIniVar As Long
Dim waarschijnlijkheidIniVar As Long
Dim risicoIniVar As Long
Dim comboIniEffect As String, comboIniWaarschijnlijkheid As String '<--| just a guess
Dim myVal As Variant '<--| variable to hold value returned by Index function
comboIniEffect = 3 '<--| following on my guess
comboIniWaarschijnlijkheid = "D" '<--| following on my guess
With Worksheets("RisicoMatrix")
If Not FindIndex(.Range("A3:A10"), comboIniEffect, "R", effectIniVar) Then Exit Sub '<--| try finding the row match, otherwise exit
If Not FindIndex(.Range("B2:I2"), comboIniWaarschijnlijkheid, "C", waarschijnlijkheidIniVar) Then Exit Sub '<--| try finding the column match, otherwise exit
myVal = Application.WorksheetFunction.index(.Range("b3:I10"), effectIniVar, waarschijnlijkheidIniVar) '<--| get value by Index function
On Error GoTo errorhandler '<--| set your error handler
risicoIniVar = CLng(myVal) '<--| try forcing value returned by Index into a Long type
On Error GoTo 0 '<--| resume standard error handling
End With
MsgBox effectIniVar & ", " & waarschijnlijkheidIniVar & ", " & risicoIniVar '<--| if everything has worked, then show: row, column and value
Exit Sub
errorhandler:
MsgBox "Error: " & Err.Number & vbCrLf & Err.Description & vbCrLf & "while forcing '" & myVal & "' into a Long" '<--| show error conditions
End Sub
Function FindIndex(rng As Range, val As Variant, rowOrCol As String, index As Long) As Boolean
Dim found As Range
With rng
Set found = .Find(what:=val, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False)
If Not found Is Nothing Then
FindIndex = True
index = IIf(UCase(rowOrCol) = "R", found.Row - .Rows(1).Row + 1, found.Column - .Columns(1).Column + 1)
End If
End With
End Function