我正在编写一个函数,该函数将数组中所选行中的所有值相加或相乘以数字(x)。但是在部分
If method = 1 Then
rng.Rows(row_number) = rng.Rows(row_number) * x
ElseIf method = 2 Then
rng.Rows(row_number) = rng.Rows(row_number) + x
End If
我收到错误消息“运行时错误424;需要对象”。
除了此代码外,我还尝试使用.Select或.entirerow.select,但没有一个起作用。
Function shiftMatrix(rg As Range, row_number As Long, x As Double, method As Integer) As Variant
Dim rng As Variant
rng = rg.value
If method = 1 Then
rng.Rows(row_number) = rng.Rows(row_number) * x
ElseIf method = 2 Then
rng.Rows(row_number) = rng.Rows(row_number) + x
End If
shiftMatrix = rng
End Function
Sub try() '
Dim rng As Variant
With Worksheets("Macro1")
rng = shiftMatrix(Worksheets("Macro1").Range("A12:AX14"), 3, 0.5, 1)
End With
End Sub
理想情况下,此函数将在Locals中显示一个数组“ rng”,这样rng(1)和rng(2)将保持不变,并且rng(3)将被加或乘以“ x”。
答案 0 :(得分:1)
看看这是否有帮助
Option Explicit
Function shiftMatrix(rg As Range, row_number As Long, x As Double, method As Long) As Variant
Dim rng As Variant
Dim i As Long
rng = rg.value
If method = 1 Then
For i = 1 To UBound(rng, 2)
If IsNumeric(rng(row_number, i)) Then rng(row_number, i) = rng(row_number, i) * x
Next i
ElseIf method = 2 Then
For i = 1 To UBound(rng, 2)
If IsNumeric(rng(row_number, i)) Then rng(row_number, i) = rng(row_number, i) + x
Next i
End If
shiftMatrix = rng
End Function
rng
是two-dimensional array,其中包含rg
范围变量中的信息。
我创建了一个循环,该循环遍历该数组中的指定记录(行)并更新(乘或加)这些值。该循环完成后,您可以将数组返回到shiftMatrix
数组,然后可以再次使用该数组填充范围。
从范围构造的二维数组的基数为1,而常规数组的标准基数为0。
在代码中,您将数组视为仍然是范围对象。更快地在数组中整体编辑范围,然后将该信息解析回范围内,而不是直接编辑Excel范围。