How to avoid using select in VBA for variable cell ranges?

前端 未结 4 709
有刺的猬
有刺的猬 2021-01-27 05:59

I have heard of the dislike for using .select in VBA for excel macros, but I am wondering how my particular goal can be achieved without its use? For example, say there is a cel

4条回答
  •  悲哀的现实
    2021-01-27 06:25

    Assuming the wanted header IS there, you can use this function:

    Function FindLowestUnfilledCell(headerRow As Range, header As String) As Range
        With headerRow.Find(What:=header, lookat:=xlWhole, LookIn:=xlValues, MatchCase:=False) '<--| look for header in passed row
            Set FindLowestUnfilledCell = headerRow.Parent.Cells(headerRow.Parent.Rows.Count, .Column).End(xlUp)
        End With
    End Function
    

    to be used by your main sub as follows

    Sub main()
    
        FindLowestUnfilledCell(Rows(1), "Commodity").Formula = "myformula"
    End Sub
    

    should the absence of the wanted header be handled, the same function gets a little longer like follows

    Function FindLowestUnfilledCell(headerRow As Range, header As String) As Range
        Dim r As Range
        Set r = headerRow.Find(What:=header, lookat:=xlWhole, LookIn:=xlValues, MatchCase:=False) '<--| look for "Commodity" in row 1
        If Not r Is Nothing Then Set FindLowestUnfilledCell = headerRow.Parent.Cells(headerRow.Parent.Rows.Count, r.Column).End(xlUp)
    End Function
    

    and its exploitation would consequently take into account the possibility of not founding the wanted header:

    Sub main()
        Dim lowestUnfilledRange As Range
    
        Set lowestUnfilledRange = FindLowestUnfilledCell(Rows(1), "Commodity")
        If Not lowestUnfilledRange Is Nothing Then lowestUnfilledRange.Formula = "myformula"
    End Sub
    

提交回复
热议问题