我正在尝试创建一个宏,它将根据VBA中的等式创建矩阵。
例如: 如果我有以下3x3矩阵:
3 5 7
6 3 4
1 2 3
我想创建一个3x3矩阵,它取第一个值并将其除以行的总和,依此类推。
0.2 0.3 0.5
0.5 0.2 0.3
0.2 0.3 0.5
我尝试了以下代码:
Sheets("sheet1").Select
Range("C2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(2, 0).Range("A1").Select 'So the new matrix starts underneath the old matrix
Dim i As Integer
Dim n As Integer
i = 4
n = 1
Do While Cells(i, 3).Value <> ""
ActiveCell.FormulaRnC1 = "=RiC3/SUM(RiC3:RiC52)*100"
i = i + 1
ActiveCell.Offset(1, 0).Range("A1").Select
数字或行会有所不同。
我对这个平台的经验有限,请让我知道如何改进框架这个问题。
答案 0 :(得分:1)
我建议你从单元格A1开始,将第一个矩阵放在Sheet1
上。这将从单元格A1开始将另一个Matrix输出到新工作簿Sheet1。
Sub example()
Dim x As Variant, y As Variant
Dim row_sum As Double
Dim i As Integer, j As Integer
Dim wbk As Workbook
With ThisWorkbook.Sheets(1)
x = .Range("a1:" & .Cells(.Range("a" & .Rows.Count).End(xlUp).Row, .Cells(1, .Columns.Count).End(xlToLeft).Column).Address).Value2
End With
y = x
With Application.WorksheetFunction
For i = LBound(x, 1) To UBound(x, 1)
row_sum = .Sum(.Index(x, i))
For j = LBound(x, 2) To UBound(x, 2)
y(i, j) = x(i, j) / row_sum
Next j
Next i
End With
Set wbk = Workbooks.Add
wbk.Sheets(1).Range("a1").Resize(UBound(y, 1), UBound(y, 2)) = y
End Sub