vba 如何使用EXCEL VBA选择一行中的单元格,直到具有特定值的单元格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25288001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:13:54  来源:igfitidea点击:

How to select cells in a row with EXCEL VBA until a cell with a certain value?

excelvbaexcel-vba

提问by user3921832

I jus want to select consequent cells in a single row, until a certain cell, with the value "Total" in it. How do I do this in VBA? I'm making a VBA procedure which relies on the length of the row, which must be dynamic (the length can change).

我只想在一行中选择后续单元格,直到某个单元格,其中包含值“总计”。我如何在 VBA 中做到这一点?我正在制作一个依赖于行长度的 VBA 过程,它必须是动态的(长度可以改变)。

回答by Patrick Honorez

Sub test()
    Dim myRow As Long
    Dim rngEnd As Range
    Dim rngToFormat As Range

    myRow = 4
    Set rngEnd = Rows(myRow).Find("total")
    If Not rngEnd Is Nothing Then
        Set rngToFormat = Range(Cells(myRow, 1), rngEnd)
        Debug.Print rngToFormat.Address
    Else
        Debug.Print "No total on row " & myRow
    End If
End Sub

回答by user3514930

Inside a sub:

在子里面:

For i = 1 To 9999
    If ActiveCell.Offset(0, i).Value = "Total" Then Exit For
    If ActiveCell.Offset(0, 1).Value = "" Then Exit For
Next
If ActiveCell.Offset(0, i).Value = "Total" Then Range(Cells(ActiveCell.Row, ActiveCell.Column), Cells(ActiveCell.Row, ActiveCell.Column + i - 1)).Select

The macro select from Activecell to the value of "Total".
If you want from the column 5 (sample):

宏从 Activecell 中选择“Total”的值。
如果你想从第 5 列(样本):

For i = 1 To 9999
    If ActiveCell.Offset(0, i).Value = "Total" Then Exit For
    If ActiveCell.Offset(0, 1).Value = "" Then Exit For
Next
If ActiveCell.Offset(0, i).Value = "Total" Then Range(Cells(ActiveCell.Row, 5), Cells(ActiveCell.Row, ActiveCell.Column + i - 1)).Select

回答by ejlj

Sub FindTotal()
    Dim rng As Variant
    rng = Rows(20) ' Then number of the row where "Total" is. Keep in mind that this will add all columns to rng and which will use a lot of memory. If you can limit the number of columns to be added e.g. rng = Range("A20:Z20") as long as Total will always be within the range
    i = 1
    While rng(1, i) <> "Total"
        i = i + 1
    Wend
End Sub