将工作表中的行或列传递给VBA函数

时间:2013-04-15 13:19:52

标签: excel-vba vba excel

我编写了一个VBA代码,用于解决一组形式为

的代数方程

A(ⅰ)X(I-1)+ B(ⅰ)X(I)+ C(I)X(I + 1)= R(I)

下面给出了部分功能。目前,系数A,B,C和R必须存储在主工作表中的列中以传递给函数。有没有办法提供在行或列中具有系数的灵活性?

Function TRIDI(ByVal Ac As Range, ByVal Bc As Range, ByVal Cc As Range, _
ByVal Rc As Range) As Variant
Dim BN As Single
Dim i As Integer
Dim II As Integer
Dim A() As Single, B() As Single, C() As Single, R() As Single, X() As Single
N = Ac.Rows.Count
ReDim A(N), B(N), C(N), R(N), X(N)
For i = 1 To N
A(i) = Ac.Parent.Cells(Ac.Row + i - 1, Ac.Column)
B(i) = Bc.Parent.Cells(Bc.Row + i - 1, Bc.Column)
C(i) = Cc.Parent.Cells(Cc.Row + i - 1, Cc.Column)
R(i) = Rc.Parent.Cells(Rc.Row + i - 1, Rc.Column)
Next i

1 个答案:

答案 0 :(得分:1)

也许您可以在函数中添加一个可选变量来指示列函数。

例如:(已编辑)

Function TRIDI(ByVal Ac As Range, ByVal Bc As Range, ByVal Cc As Range, ByVal Rc As Range) As Variant


    Dim BN As Single
    Dim i As Integer
    Dim II As Integer
    Dim ColumnN As Boolean
    Dim A() As Single, B() As Single, C() As Single, R() As Single, X() As Single

    If Ac.Rows.Count = 1 Then
        N = Ac.Columns.Count
        ColumnN = True
    Else If Ac.Columns.Count = 1 Then
        N = Ac.Rows.Count
    Else
        Exit Function
    End If

    ReDim A(N), B(N), C(N), R(N), X(N)

    If ColumnN = True Then
        For i = 1 To N

            A(i) = Ac.Parent.Cells(Ac.Row, Ac.Column + i - 1)
            B(i) = Bc.Parent.Cells(Bc.Row, Bc.Column + i - 1)
            C(i) = Cc.Parent.Cells(Cc.Row, Cc.Column + i - 1)
            R(i) = Rc.Parent.Cells(Rc.Row, Rc.Column + i - 1)

        Next i
    Else
        For i = 1 To N

            A(i) = Ac.Parent.Cells(Ac.Row + i - 1, Ac.Column)
            B(i) = Bc.Parent.Cells(Bc.Row + i - 1, Bc.Column)
            C(i) = Cc.Parent.Cells(Cc.Row + i - 1, Cc.Column)
            R(i) = Rc.Parent.Cells(Rc.Row + i - 1, Rc.Column)

        Next i
    End If


End Function

我可能错过了示例中函数的一些功能,但我认为你明白了。如果这不起作用给我反馈,生病尝试另一种解决方案。 :)

编辑:您还可以将函数设置为一个函数,该函数接收来自另外两个名为CTRIDI和RTRIDI的函数的输入。这两个函数只是将以下的true或false传递给列变量。