【问题标题】:How to select specific rows from an array containing row Indexes in excel with vba如何使用vba从包含行索引的数组中选择特定行
【发布时间】:2019-08-07 22:17:32
【问题描述】:

我正在处理一个长长的 Excel 列表,我必须选择符合条件的特定行。我设法创建了一个包含这些行的索引号的数组。我现在要做的就是选择那些行。

代码如下:

Sub Playground()

Dim currentContract As String
currentContract = "none"
Dim CCIsPos As Boolean
CCIsPos = False
Dim asarray() As Integer
Dim i As Integer

ReDim asarray(1 To Sheets("Playground").UsedRange.Rows.Count)
For Each Cell In Sheets("Playground").Range("E:E")

    matchRow = Cell.Row

    If Cell.Value <> currentContract Then
        currentContract = Cell.Value
        If Cells(matchRow, "J") > 0 Then
            CCIsPos = True
        Else
            CCIsPos = False
        End If
       End If
If CCIsPos Then
    i = i + 1
    asarray(i) = matchRow
End If
Next Cell

'Would need a function here selecting rows from the array "asarray"
'Rows(asarray).Select doesn't work.
End Sub

【问题讨论】:

  • 使用逗号“,”范围运算符,您可以创建一个字符串并像这样使用它:range("a1, a4, a6").Entirerow.Select
  • 如果您有超过 16383 行,使用 Integer 类型是有问题的。建议将Integer 的所有实例替换为Long,这是一个32 位整数值。 Integer 类型只有 16 位宽。 (见stackoverflow.com/a/31816532/380384

标签: excel vba


【解决方案1】:

我会说你需要使用Union() 函数。修改您的代码如下,我假设您已经检查并确认 asarray 包含正确的行索引,我不会查看这些部分。

Sub Playground()

Dim currentContract As String
currentContract = "none"
Dim CCIsPos As Boolean
CCIsPos = False
Dim i As Integer
Dim selectionRange as Range

For Each Cell In Sheets("Playground").Range("E:E")
    matchRow = Cell.Row
    If Cell.Value <> currentContract Then
        currentContract = Cell.Value
        If Cells(matchRow, "J") > 0 Then
            CCIsPos = True
        Else
            CCIsPos = False
        End If
    End If
    If CCIsPos Then
        If Not selectionRange Is Nothing Then
            Set selectionRange = Union(selectionRange, Sheets("Playground").Rows(matchRow).EntireRow)
        Else
            Set selectionRange = Sheets("Playground").Rows(matchRow).EntireRow
        End If
    End If
Next Cell

selectionRange.Select

End Sub

希望这能解决您的问题。

【讨论】:

  • 如所写,此代码在第一次尝试Union 时总是会出错,因为当时selectionRange 将是Nothing,您不能合并一个空范围。需要测试selectionRange 是否为空,如果是,只需将其设置为符合条件的范围,否则如图所示联合。您还需要确保在分配对象变量(例如范围)时使用Set关键字,所以它应该是Set selectionRange = ...
  • 你是对的,这也表明我应该在发布之前测试我的答案:) 我已经进行了相关的编辑,谢谢你的警告。
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 2020-06-23
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 2011-05-27
  • 2019-05-22
  • 1970-01-01
相关资源
最近更新 更多