我有一张纸,上面有一堆物品,每个物品都有一个ID号,描述,概率(1-5),风险值(1-5)和状态。在下面的矩阵中,概率列用作Y轴,风险列用作X轴。因此,对于每种(x,y)组合,我都希望将相应的ID号和状态附加到矩阵中的正确单元格中。因此,例如,使用概率= 1和风险= 1的值,风险矩阵中的A1单元会更新该项目的ID和状态。
风险矩阵 Risk Matrix Output Desired
我的数据示例: Small sample of cells
答案 0 :(得分:2)
主要-您(应该)只需要更改矩阵和ID号的范围
Sub main()
Dim wsMatrix As Worksheet
Dim wsData As Worksheet
Dim RiskMatrixCells As range
Dim idsToAppend As range
Dim riskMatrixAddresses As Variant
Set wsMatrix = Sheets("Matrix")
Set wsData = Sheets("Data")
Set RiskMatrixCells = wsMatrix.range("C3:G7")
riskMatrixAddresses = GetArrayOfRangeAddresses(RiskMatrixCells)
Set idsToAppend = wsData.range("A2:A11")
Call AppendMatrixWithIds(riskMatrixAddresses, idsToAppend, wsMatrix)
End Sub
第一个功能
Function GetArrayOfRangeAddresses(ByRef targetRng As range) As Variant()
Dim numTargetRngRows As Integer
Dim numTargetRngColumns As Integer
Dim currentCell As range
Dim arrayOfRangeAddresses As Variant
numTargetRngRows = targetRng.Rows.Count - 1
numTargetRngColumns = targetRng.Columns.Count - 1
ReDim arrayOfRangeAddresses(numTargetRngRows, numTargetRngColumns)
x = 0
y = 0
For Each currentCell In targetRng
arrayOfRangeAddresses(x, y) = CStr(Replace(currentCell.AddressLocal, "$", ""))
If y = numTargetRngRows Then
y = 0
x = x + 1
Else
y = y + 1
End If
Next currentCell
GetArrayOfRangeAddresses = arrayOfRangeAddresses
End Function
第二功能
Sub AppendMatrixWithIds(ByRef matrixArray As Variant, ByVal idsToAppend As Range, ByRef ws As Worksheet)
Dim currentCell As Range
Dim prob As Long
Dim risk As Long
Dim status As String
For Each currentCell In idsToAppend
prob = currentCell.Worksheet.Cells(currentCell.Row, 3)
risk = currentCell.Worksheet.Cells(currentCell.Row, 4)
status = currentCell.Worksheet.Cells(currentCell.Row, 5)
ws.Range(matrixArray(prob - 1, risk - 1)).Value = currentCell.Value + "|" + status _
+ " " + ws.Range(matrixArray(prob - 1, risk - 1)).Value
Next currentCell
End Sub