我正在尝试编写一个函数,该函数采用一系列数据并从用户提供的列中计算两个数字的比率。我想在行尾打印这个比率,但由于某种原因,我无法使用单元格函数引用行中的最后一个单元格。相反,Cells 函数只是不断地向我提供该单元格的值,而不是单元格地址。我认为细胞功能也提供了地址。有人可以告诉我这是错误的还是我的代码错误?
这是代码
Function calculateRatio(table As Range, numerator As Integer, denominator As Integer, Optional nameOfRatio As String)
On Error GoTo ExpectedError
Dim num As Double
Dim denom As Double
Dim ratio As Double
If table.Columns.Count < 2 Then
MsgBox ("Not enough data. Requires at least two or more rows.")
Exit Function
End If
If numerator < 1 Or numerator > table.Columns.Count Then
MsgBox ("Not an acceptable Numerator. Must be greater than zero and less than " & table.Columns.Count)
Exit Function
End If
If denominator < 1 Or denominator > table.Columns.Count Then
MsgBox ("Not an acceptable Denominator. Must be greater than zero and less than " & table.Columns.Count)
Exit Function
End If
For Counter = 1 To table.Rows.Count
num = table.cells(Counter, numerator)
denom = table.cells(Counter, denominator)
ratio = num / denom
temp = table.cells(counter, table.columns.count)
temp.Offset(0, 1).Value = ratio
Next Counter
Exit Function
ExpectedError:
Call MsgBox("Something went wrong. Make sure you are referencing columns with numbers and not text." & Err.Number & " : " & Err.Description)
End
End Function
更新
这是更新的代码:
Function calculateRatio(table As Range, numerator As Integer, denominator As Integer, Optional nameOfRatio As String)
Dim num As Double
Dim denom As Double
Dim ratio As Double
Dim temp As Range
Dim counter As Integer
If table.Columns.Count < 2 Then
MsgBox ("Not enough data. Requires at least two or more rows.")
Exit Function
End If
If numerator < 1 Or numerator > table.Columns.Count Then
MsgBox ("Not an acceptable Numerator. Must be greater than zero and less than " & table.Columns.Count)
Exit Function
End If
If denominator < 1 Or denominator > table.Columns.Count Then
MsgBox ("Not an acceptable Denominator. Must be greater than zero and less than " & table.Columns.Count)
Exit Function
End If
For counter = 1 To table.Rows.Count
num = table.cells(counter, numerator)
denom = table.cells(counter, denominator)
ratio = num / denom
Set temp = table.cells(counter, table.Columns.Count)
temp.Offset(0, 1).Value = ratio
Next counter
End Function