首页 > 解决方案 > 在 Visual Basic 中使用范围和集合

问题描述

我有2个相同的矩阵。它们有单元格:第一个矩阵有 a11、a12、...、aij 单元格,第二个矩阵有 b11、b12、...、bij 单元格。我需要写一个公式=A11*B11 + A12*B12 + A13*B13 ... + Aij*Bij,依此类推,直到矩阵的右下角。我想在矩阵 10 x 10 时不浪费时间做宏,因为写这样的公式 100 次需要很长时间。我有代码:

Sub myMacros()
  'where to
  Dim form As String
  form = "="

'Choose cell where to put formula
Dim whereToPutFormula As Range
Set whereToPutFormula = Application.InputBox("Choose cell where to put formula", Type:=8)

'Range of first and second matrix
Dim firstMatrix As Range

Set firstMatrix = Application.InputBox("Range of the first matrix", Type:=8)
Dim secondMatrix As Range
Set secondMatrix = Application.InputBox("Range of the second matrix", Type:=8)

col_number = InputBox("How many columns in matrix")
row_number = InputBox("How many rows in matrix")

'variables for loop
Dim Rows As Integer
Dim Columns As Integer

'loop for formula
For Rows = 1 To row_number
    For Columns = 1 To col_number
        'val_from_firstMatrix = Range(firstMatrix).Cells().Value2
        'val_from_secondMatrix = Range(secondMatrix).Cells().Value2
        If Rows = row_number And Columns = col_number Then
            form = form & Range(firstMatrix).Cells(Rows, Columns).Address(RowAbsolute:=False, ColumnAbsolute:=False) & "*"
            form = form & Range(secondMatrix).Cells(Rows, Columns).Address(RowAbsolute:=False, ColumnAbsolute:=False)
            Debug.Print form
        Else:
            form = form & Range(firstMatrix).Cells(Rows, Columns).Address(RowAbsolute:=False, ColumnAbsolute:=False) & "*"
            form = form & Range(secondMatrix).Cells(Rows, Columns).Address(RowAbsolute:=False, ColumnAbsolute:=False) & " + "
            Debug.Print form
        End If
    Next Columns
Next Rows

End Sub

但它返回一个错误

错误 1004,对象“_Global”字段的方法“范围”。

在 if 条件下。我应该改变什么才能让它工作?

标签: excelvba

解决方案


根据我们在评论中的讨论,我发布以下内容:

你的问题让我很困惑。似乎您有重叠矩阵(10x10一个开始,A11第二个B11?)。

大概您的错误在包含Range(firstMatrix). firstMatrix是一个Range对象。以这种方式使用的对象的参数Range需要是范围的名称而不是另一个范围对象。

另请注意,您问题中的公式:=A11*B11 + A12*B12 + A13*B13等效于:=SUMPRODUCT(A11:A13,B11:B13)

如果您的矩阵只是单列,那将与

`=SUMPRODUCT(A11:An,B11:Bn)

推荐阅读