输入框VBA,输入列名称而不是指定

时间:2015-04-27 12:26:49

标签: vba excel-vba excel

我创建了一个程序,要求输入Column然后创建60个值的平均值,然后创建接下来的60个值,依此类推。我想要列(A,B)输入的输入我将输入已命名列的变量,就像列L已被命名为Power。所以我输入的是电源而不是L.

Sub Hourlyaverage()
    Dim i As Long, j As Long, k As Long
    Dim myRange As Range
    Dim myValue As Variant

    Sheets("DUT1_Test51_excel").Select

    i = 3
    j = 3
    k = 63

    myValue = InputBox("Give Column name to calculate Average eg. A,B")

    Do While Cells(i, 12).Value <> ""
        Set myRange = Range(myValue & i & ":" & myValue & k)
        Cells(j, 20).Value = Application.Average(myRange)
        i = i + 60
        j = j + 1
        k = k + 60
    Loop   
End Sub 

2 个答案:

答案 0 :(得分:1)

您可以添加一个自定义函数,给定一个值,它将返回列:

Public Function valueToColumn(ByVal val As String) As String

    valueToColumn = Split(ActiveSheet.Range("A:Z").Find(val).Address, "$")(1)

End Function

因此,一旦用户获得输出,您需要做的就是将myValue转换为包含myValue = valueToColumn(myValue)的列字母。

请注意:

  • 以上搜索范围A-Z中的值。您需要根据需要进行调整。
  • 以上,如果未找到该值,则会引发异常Variable not set。您需要使用错误处理程序来管理它(我允许您根据需要选择最佳)。

答案 1 :(得分:0)

如果您使用第一行命名列,请使用此列。将colEnd更改为使用的列数。或者从vba获取使用的列。

Sub Hourlyaverage()
    Dim i As Long, j As Long, k As Long
    Dim myRange As Range
    Dim myValue As Variant

    'variables for Column Names
    Dim colEnd As Long, x As Long
    Dim colName As String


    Sheets("DUT1_Test51_excel").Select

    i = 3
    j = 3
    k = 63

    myValue = InputBox("Give Column name to calculate Average eg. A,B")

    'Set columns used
    colEnd = 5

    For x = 1 To colEnd
        If Ucase(Cells(1, x).Value) = Ucase(myValue) Then colName = Right(Left(Cells(1, x).Address, 2), 1)
    Next
    'If column name is not used it will take the value of myValue to see try and use that as a column name incase the user does not use the full name.
    'Tries the first letter incase it was spelt wrong.
    If colName = "" Then colName = Left(UCase(myValue),1)

    Do While Cells(i, 12).Value <> ""
        Set myRange = Range(colName & i & ":" & colName & k)
        Cells(j, 20).Value = Application.Average(myRange)
        i = i + 60
        j = j + 1
        k = k + 60
    Loop
End Sub