简体   繁体   English

如何在excel vba中对用户定义的范围执行操作?

[英]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). 我想有一个for循环,用于对A列(1)中的第一个值,B列(3)中的邻近值和C列(74)中的邻近值进行平均。 I would need the user to choose this range with a msgbox. 我需要用户使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使Excel用户定义函数(UDF)接受字符串类型和范围类型的参数? - How do I make Excel user-defined function (UDF) accept arguments of String type and range type? 在 Excel VBA 中,如何保存/恢复用户定义的过滤器? - In Excel VBA, how do I save / restore a user-defined filter? 如何在Microsoft VBA中解决此错误消息“编译错误:未定义用户定义类型” - How can I resolve this error message “Compile Error: User-defined type not defined” in Microsoft VBA 在Excel VBA上返回用户定义的类型 - Returning user-defined types on Excel VBA VBA Excel中的用户定义函数是不可访问的? - User-defined Function in VBA Excel is Not Accessible? 如何在VBA Excel中使用定义的范围名称? - How can I use my defined name of range in VBA Excel? Excel VBA-将变量分配给位于某些单元格范围内的用户定义的公式 - Excel VBA - Assigning Variable to a User-Defined Formula Located in Some Cell Range 在Excel用户定义函数中,如何确定使用哪种字体? - In an Excel User-Defined function, how can I determine which font is being used? Excel VBA 编译抛出“未定义用户定义的类型”错误 - Excel VBA Compile throws a “User-defined type not defined” error excel vba userforms:未定义的用户定义类型 - excel vba userforms: user-defined type not defined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM