如何在VBA中引用可变矩阵中的整个列或行?

时间:2018-09-19 09:56:02

标签: arrays excel vba matrix reference

我已经花了很多时间寻找一种方法,该方法如何引用我在VBA中创建的矩阵中的范围(列或行)。

一个简单的示例是遍历4 x x矩阵的第4行,以对x列的第1到3列求和。

下面的代码是很长的路要走:

.video-iframe {
    width: 100%;
    height: 350px;
    border: 5px solid #fff;
    border-radius: 4px;
}

我正在寻找一种做到这一点而又没有错误的方法:

@media screen and (max-width: 600px) {

    .video-iframe {
        margin-top: 50px;
        width: 100%;
        height: 250px;
        border: 5px solid #fff;
        border-radius: 4px;

    }

当我尝试运行它时弹出以下错误:

x = 10 Dim Matrix() As Variant ReDim Matrix(1 to 4, 1 to x) For c = 1 to x Matrix(4, c) = Application.WorksheetFunction.Sum(Matrix(1, c), Matrix(2, c), Matrix(3, c)) Next

由于其他解决方法似乎很耗时,因此请您帮忙解决此问题。

谢谢!

安迪

1 个答案:

答案 0 :(得分:1)

正如James Poag所说,range不是全局函数,必须与工作表一起调用。如果要使用WorksheetFunction.Sum,则必须将矩阵复制到工作表中。在下面的示例中:

  1. 创建一个4 x 10的随机数矩阵
  2. 创建一个新的工作表,
  3. 将矩阵复制到工作表中,
  4. 使用WorksheetFunction.Sum添加范围的行,然后
  5. 删除由VBA宏添加的工作表

    Option Explicit
    
    Public Sub Matrixer()
        Dim x As Long
        x = 10
        Dim matrix() As Double
        ReDim matrix(1 To 4, 1 To x)
    
        'Generate the matrix
        Dim rowNDX As Long
        Dim colNDX As Long
        For rowNDX = 1 To UBound(matrix, 1)
            For colNDX = 1 To UBound(matrix, 2)
                Randomize
                matrix(rowNDX, colNDX) = Rnd
            Next colNDX
        Next rowNDX
    
        'Write the maxtrix to a sheet
        'First add a worksheet to do the calculation
        Dim wb As Workbook: Set wb = ActiveWorkbook
        Dim strName As String: strName = "MATRIXCALC"
    
        Dim ws As Worksheet
        Set ws = wb.Worksheets.Add(Type:=xlWorksheet)
        With ws
            .Name = strName
        End With
    
        'Write the maxtrix to the sheet
        'This code was provide/adapted from Chip Pearson's blog at
        'http://www.cpearson.com/excel/ArraysAndRanges.aspx
        Dim Destination As Range
        Set Destination = ws.Range("A1")
        Destination.Resize(UBound(matrix, 1), UBound(matrix, 2)).Value = matrix
    
        'Use the worksheet function to Sum the range
        Dim RowSum(4) As Double
        Dim rngSum As Range
        For rowNDX = 1 To 4
            Set rngSum = ws.Range("A" & Trim(CStr(rowNDX)) & ":A" & Trim(CStr(UBound(matrix, 2))))
            RowSum(rowNDX) = WorksheetFunction.Sum(rngSum)
    
        Next rowNDX
    
        'Delete the worksheet added by the macro
        'Prevent asking user if it's ok to delete worksheet
        Application.DisplayAlerts = False
        ws.Delete
        'Turn application display alerts back on.
        Application.DisplayAlerts = True
    End Sub