将公式应用于整个范围

时间:2013-03-12 22:11:57

标签: excel excel-vba range formula user-defined vba

对于经过实验的VBA开发人员/用户来说,这可能是一段非常简单的代码,但是我已经在新的编程中坚持了几天这个任务:(。我只需要将一个公式应用于用户定义的范围整体(如果可能)或循环通过它“for-each next”或“for next”我只是为我尝试过的每一次尝试都会犯错误。任何人都可以帮我解决这个问题,请... ..thxs提前很多

让我们说公式很容易,因为F = m * a,“m”是我选择的范围

这里是选择范围的代码:

Option Base 1


    Sub KVmodel()

    'Select the data points from the excel spreadsheet

    Dim A, B As Range
    Set A= Application.InputBox("Select A Range", "Select a range", Type:=8)
    Set B= Application.InputBox("Select B Range", "Select a range", Type:=8)


    'Verify the lenght of the selected data
    If A.Count = B.Count Then
    MsgBox "Do you want to run the KV Model Adjustment?", vbYesNo


    'Calculates F according to the values of the model

    -
    -
    -


    Else
    MsgBox "The range sizes are different, please re-select the input data"

    End If

    End Sub

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

Option Base 1


Sub KVmodel()

    On Error Resume Next

    'Select the data points from the excel spreadsheet

    Dim A As Range, B As Range
    Set A = Application.InputBox("Select A Range", "Select a range", Type:=8)
    Set B = Application.InputBox("Select B Range", "Select a range", Type:=8)

    Dim userDefinedRng As Range ' assumption
    Set userDefinedRng = Range("A1:A10")

    On Error GoTo 0

    If Not A Is Nothing And Not B Is Nothing Then

        'Verify the lenght of the selected data
        If A.Count = B.Count Then
            retVal = MsgBox("Do you want to run the KV Model Adjustment?", vbYesNo)

            If retVal = vbYes Then
                'Calculates F according to the values of the model
                userDefinedRng.FormulaR1C1 = "= 1 * 2" ' here it applies forumla to whole userdefined range
                MsgBox "yes"
            Else
                MsgBox "no"
            End If

        Else
            MsgBox "The range sizes are different, please re-select the input data"

        End If
    End If

    Exit Sub

End Sub