excel - 在 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 条件下。我应该改变什么才能让它工作?
解决方案
根据我们在评论中的讨论,我发布以下内容:
你的问题让我很困惑。似乎您有重叠矩阵(10x10
一个开始,A11
第二个B11
?)。
大概您的错误在包含Range(firstMatrix)
. firstMatrix
是一个Range
对象。以这种方式使用的对象的参数Range
需要是范围的名称,而不是另一个范围对象。
另请注意,您问题中的公式:=A11*B11 + A12*B12 + A13*B13
等效于:=SUMPRODUCT(A11:A13,B11:B13)
如果您的矩阵只是单列,那将与
`=SUMPRODUCT(A11:An,B11:Bn)
推荐阅读
- git - 如何从同一个分支创建第二个新的拉取请求?
- flutter - 如何在 FutureProvider 中读取 StateNotifierProvider 状态
- css - 更漂亮的不在 React 中格式化 CSS 代码
- django - pytest 夹具来制作我有参数的 AIPClient
- android - 未显示应用时,Android 前台停止
- javascript - Material UI 网格间距之谜
- 3d - 3D boids 逃逸边界框,p5js
- python - 从字符串中删除新行而不删除“\n”?
- python - OneHotEncoding 用于分类数据
- python - Python/Selenium - 单击按钮