循环并选择

时间:2020-05-07 14:20:20

标签: excel vba loops variables select

我目前正在尝试找出如何在A列中循环搜索变量,我想从该单元格到最后一行以及其他2列B和C选择范围(最后一行相同的变量)。

我尝试过

Sub TretourTdepart
    Dim LastRow As Long
    Dim sh As Worksheet
    Dim X As Long

    Set sh = Sheets("data_(6)") 'Define sheet to copy from

    LastRow = sh.Cells(Rows.Count, 1).End(xlUp).Row 'Find last row to copy from

    For X = 2 To LastRow
        If sh.Cells(X, 1) = "variable" Then
            Set Rng = Range(sh.Cells(LastRow, 1), sh.Cells(X, 1))
            Rng.Select
          End If
      Next
End Sub

但是上面的脚本没有选择我想要的单元格范围。

1 个答案:

答案 0 :(得分:1)

您实际上不需要循环,如果可以保证您的工作表具有“变量”条目,则可以使用match函数:

Sub TretourTdepart()

Dim LastRow As Long
Dim VariRow As Long
Dim sh As Worksheet
Dim rng As Range

Set sh = Sheets("data_(6)") 'Define sheet to copy from

LastRow = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row 'Find last row to copy from
VariRow = Application.WorksheetFunction.Match("variable", sh.Range("A:A"), 0)

Set rng = sh.Range(Cells(VariRow, 1), Cells(LastRow, 3))

End Sub

如果不能保证“变量”条目在那里,则可以将其包装在if检查中:

编辑我在评论中看到您的“变量”实际上是一个字符串,因此已将其设置为实际变量MyVariable

Sub TretourTdepart()

Dim LastRow As Long
Dim VariRow As Long
Dim sh As Worksheet
Dim rng As Range
Dim MyVariable As String: MyVariable = "ElectricityMeter"

Set sh = Sheets("data_(6)") 'Define sheet to copy from

LastRow = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row 

If Application.WorksheetFunction.CountIf(sh.Range("A:A"), MyVariable) > 0 Then
    VariRow = Application.WorksheetFunction.Match(MyVariable, sh.Range("A:A"), 0)
    Set rng = sh.Range(Cells(VariRow, 1), Cells(LastRow, 3))
End If

End Sub
相关问题