Cells reference not working in Excel VBA 2010 Function

前端 未结 3 1171
长发绾君心
长发绾君心 2020-12-11 12:01

I am attempting to write a function that takes a range of data and calculates the ratio of two numbers from the columns provided by the user. I want to print this ratio out

3条回答
  •  时光说笑
    2020-12-11 12:33

    I'm assuming you're not using Option Explicit in your code.

    You need to declare "temp" as a range.

    Dim temp As Range ' somewhere at the top of your function
    
    For Counter = 1 To table.Rows.Count
    ......
    Set temp = table.cells(Counter, table.columns.count)
    ...
    Next
    

    If you've got the cell coordinates why not offset it manually?

    table.cells(counter, table.Columns.Count+1).Value = ratio
    

    Try this:

    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
            table.cells(counter, table.Columns(table.Columns.Count).Column + 1).Value = ratio
            'Set temp = table.cells(counter, table.Columns.Count)
            'temp.Offset(0, 1).Value = ratio
        Next counter
    End Function
    

    Using `table.columns(table.columns.count).column will make sure that your referencing the correct column, cant think of an example that would cause problems at the moment but better to be safe.

提交回复
热议问题