简体   繁体   中英

How can I perform an operation in excel vba for an user-defined range?

I have a series of cells with values ie

在此处输入图片说明

I would like to have a for loop that is doing the average of the first value in column A (1), the adjacent value in column B (3) and the adjacent value in column C (74). I would need the user to choose this range with a msgbox.

So far I could code this, with the help from the macro recording:

Sub averager()
    Dim ran As Range, average As Variant, cell1 As Variant, cell2 As Variant
    Dim i As Variant

    Set ran = Application.InputBox(Prompt:="Enter range values: ", Type:=8)

    For i = 0 To i = 8
        ran.Offset(0, 13).Select
        ActiveCell.FormulaR1C1 = "=AVERAGE(RC[-13]:RC[-11])"
        average = WorksheetFunction.average(ran.Text)
    Next i
End Sub

However, this code doesn't perform the loop and it returns only the first triplicate's average in the offset position I chose.

How can the loop perform the operation for all the values?

  1. Catch the error in case the user presses the Cancel button.
  2. You don't need a loop, you can write the formula to multiple cells at once.

Option Explicit

Public Sub Averager()        
    Dim ValueRange As Range
    On Error Resume Next 'if user presses cancel this throws an error
    Set ValueRange = Application.InputBox(Prompt:="Select range values: ", Type:=8)
    On Error GoTo 0

    If Not ValueRange Is Nothing Then
        ValueRange.Offset(ColumnOffset:=6).Resize(ColumnSize:=1).FormulaR1C1 = "=AVERAGE(RC[-6]:RC[-4])"
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM