VBA不同纸张上的两个二维数组的总和

我试图在SheetB上添加/减去SheetA上/从matrix的matrix,并在SheetA + B上打印结果。 此代码工作,但是当我使用matrix不是正方形,那么我得到的错误下标超出范围。 任何想法做什么? matrixA和B的大小相同,但大小是用户定义的,始终以A1开头。

Private Sub CommandButton5_Click() '''''''''''''''''''A+B''''''''''''''''''''''''' 'determining matrix size Worksheets("A").Activate Dim a As Integer Dim b As Integer lastcol = ActiveSheet.Range("a1").End(xlToRight).Column lastrow = ActiveSheet.Cells(65536, lastcol).End(xlUp).Row a = lastcol b = lastrow Dim matricaA As Range Dim matricaB As Range With Sheets("A") lastcol = ActiveSheet.Range("a1").End(xlToRight).Column lastrow = ActiveSheet.Cells(65536, lastcol).End(xlUp).Row Set matricaA = ActiveSheet.Range("a1", ActiveSheet.Cells(lastrow, lastcol)) End With With Sheets("B") 'lastcol = ActiveSheet.Range("a1").End(xlToRight).Column 'lastrow = ActiveSheet.Cells(65536, lastcol).End(xlUp).Row Set matricaB = ActiveSheet.Range("A1", ActiveSheet.Cells(lastrow, lastcol)) End With Dim rngA As Range Dim rngB As Range Dim rngSum As Range Dim arrA As Variant Dim arrB As Variant Dim arrSum As Variant Worksheets("A").Activate With Sheets("A") lastcol = ActiveSheet.Range("a1").End(xlToRight).Column lastrow = ActiveSheet.Cells(65536, lastcol).End(xlUp).Row Set rngA = ActiveSheet.Range("a1", ActiveSheet.Cells(lastrow, lastcol)) End With Worksheets("B").Activate With Sheets("B") lastcol = ActiveSheet.Range("a1").End(xlToRight).Column lastrow = ActiveSheet.Cells(65536, lastcol).End(xlUp).Row Set rngB = ActiveSheet.Range("A1", ActiveSheet.Cells(lastrow, lastcol)) End With Application.Goto ActiveWorkbook.Sheets("A+B").Range("A1").Resize(b, a) Worksheets("A+B").Activate With Sheets("A+B") lastcol = b lastrow = a Set rngSum = ActiveSheet.Range("A1", ActiveSheet.Cells(lastrow, lastcol)) End With arrA = rngA.Value arrB = rngB.Value arrSum = rngSum.Value Dim x As Integer, y As Integer For x = LBound(arrA, 1) To UBound(arrA, 1) For y = LBound(arrA, 2) To UBound(arrA, 2) arrSum(x, y) = arrA(x, y) + arrB(x, y) '...error - subscript out of range Next ' when matrix is non square Next 'Print result to sheet rngSum.Value = arrSum End Sub 

 Dim rng as Range Set rng = worksheets("A").Range("A1").currentregion rng.copy worksheets("A+B").range("A1") worksheets("A").Range(rng.address()).copy worksheets("A+B").range("A1").pastespecial Paste:=xlPasteValues, Operation:=xlAdd 
Interesting Posts