VBA - 根据标题值设置功能范围

时间:2014-08-02 21:12:35

标签: vba excel-vba find range excel

我是VBA的新手,所以我需要一些帮助来完成我正在进行的这个项目。我正在尝试编写一个易于扩展和扩展的脚本,因此我尽可能避免使用硬代码值。我也不想在我的代码中使用任何Excel函数。我有一个计算范围平均值的函数。我有一个子程序将avg打印到一个单独的文本文件。但是,我不想硬编码我需要取平均值的范围。是否可以搜索标题(不使用“查找”),然后指定标题下方的值范围?

这是我到目前为止所拥有的。请注意,该范围现在是硬编码的。这样可以完美地工作,但我需要它更灵活,以防数据不总是以相同的方式呈现。

Function AvgMS(Rng As Range) As Double

    Total = 0
    Count = 0

    For Each cell In Rng

        If Not IsEmpty(cell) Then

            Total = Total + cell.Value
            Count = Count + 1

        End If

    Next cell

    AvgMS = Total / Count

End Function

Sub Average() 'Generate CSV File

  Dim FilePath As String
  Dim AMS As Double

  'Directory Address
  FilePath1 = "Macintosh HD:Users:Me:Documents:Project:avg.csv"
  FileNum = FreeFile

  Open FilePath1 For Output As #FileNum

  AMS = AvgMS(Range(Range("B2"), Range("B2").End(xlDown))) 'Define Data Range for AvgMS Function

  Print #FileNum, AMS ' Print text to file.

  Close #FileNum ' Close file.

  MsgBox ("avg.csv successfully updated")

End Sub

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码搜索文本"标题"在"使用范围" of" Sheet1":

Function FindFirstOccurrence(FindString As String) As Range
    Dim rng As Range
    If Trim(FindString) <> "" Then
        With Sheets("Sheet1").UsedRange
            Set rng = .Find(What:=FindString, _
                            After:=.Cells(.Cells.Count), _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=False)
            If Not rng Is Nothing Then
                Set FindFirstOccurrence = rng
            Else
                Set FindFirstOccurrence = Nothing
            End If
        End With
    End If
End Function

Sub Test()
    Dim rng As Range
    Set rng = FindFirstOccurrence("Header")
    If Not rng Is Nothing Then
        MsgBox rng.Address
    Else
        MsgBox "Not found"
    End If
End Sub

我希望您能够根据您的要求进行调整,但如果您需要更多解释,请告诉我。

答案 1 :(得分:0)

想出了这个简单的解决方案,它确实有效。有什么问题吗?

   'Find column where the  data is located and set range
    i = 1
    Do Until Cells(1, i) = "Text"
    i = i + 1
    Loop

    CellNum = Cells(1, i).Offset(1, 0).Address(RowAbsolute:=False, ColumnAbsolute:=False)

    'Set the range for AMS Function
    Set MSrng = Range(CellNum, Range(CellNum).End(xlDown))l