循环并选择

问题描述 投票:0回答:1

我目前正试图弄清楚如何循环使用 可变的 在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

但是上面的脚本并没有按照我的要求选择单元格的范围。

excel vba loops variables select
1个回答
1
投票

你真的不需要循环,如果你的工作表保证有 "变量 "条目,你可以使用匹配函数。

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
© www.soinside.com 2019 - 2024. All rights reserved.