如何避免在VBA中使用select用于可变单元格范围?

时间:2016-08-08 15:52:05

标签: excel vba excel-vba

我听说过不喜欢在VBA中使用.select for excel宏,但我想知道如何在没有使用它的情况下实现我的特定目标?例如,假设有一个单元格(用作标题),其值为" Commodity"。在它下面,所有细胞都需要具有VLookup功能。但是,在宏的每次迭代中,列都将移位(添加新列时)并添加新行(因此新添加的行也需要添加该函数)。如何一致地找到此商品列并找到其最低的未填充行?使用select:

非常简单
Do Until ActiveCell.Value = "Commodity"
Activecell.offset(0,1).select
loop
Do Until ActiveCell.Value = ""
ActiveCell.offset(1,0).select
loop

显然,我宁愿避免使用这种语法,但我不知道如何解决它。我所看到的关于避免选择的所有答案似乎都设置了,例如,rng = Cell(x,y)或其他东西,但它们总是已知的位置单元格。如果不使用select来检查单元格值,我不知道如何做到这一点。

4 个答案:

答案 0 :(得分:3)

首先找到Sting所在的列,然后计算它旁边的行,设置范围并输入公式。

Sub FindColumn()
    Dim f As Range, c As Integer
    Dim LstRw As Long, rng As Range

    Set f = Rows(1).Find(what:="Commodity", lookat:=xlWhole)

    If Not f Is Nothing Then
        c = f.Column
    Else: MsgBox "Not Found"
          Exit sub

    End If

    LstRw = Cells(Rows.Count, c - 1).End(xlUp).Row
    Set rng = Range(Cells(2, c), Cells(LstRw, c))
    rng = "My Formula"

End Sub

答案 1 :(得分:0)

以下是基于ActiveCell的两个迭代行。

Sub Examples()

    Dim Target As Range
    Dim x As Long

    Set Target = ActiveCell

    Do Until Target.Value = "Commodity"
        Set Target = Target.Offset(0, 1)
    Loop

    Do Until ActiveCell.Offset(x, 1).Value = ""
        x = x + 1
    Loop

End Sub

答案 2 :(得分:0)

假设有所需的标题IS,您可以使用此功能:

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

将由您的主要子项使用,如下所示

Sub main()

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

如果没有处理想要的标题,那么相同的函数会像下面的

那样长一点
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
因此,它的利用将考虑到没有找到所需标题的可能性:

Sub main()
    Dim lowestUnfilledRange As Range

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

答案 3 :(得分:0)

我想稍微简化一下答案。例如

Set r = ActiveCell
MsgBox r.Address    ' $A$1
Columns("A").Insert ' insert column before the first column
MsgBox r.Address    ' $B$1

因此您可以将代码更改为

Dim cell As Range   ' optional
Set cell = ActiveCell
While cell = "Commodity"
    Set cell = cell(, 2)    ' similar to Set cell = cell.Resize(1,1).Offset(, 1)
Wend
While cell = ""
    Set cell = cell(, 2)
Wend