【问题标题】:Excel array Populated with non blank values of listobject column rangeExcel 数组填充了 listobject 列范围的非空白值
【发布时间】:2019-12-17 00:16:01
【问题描述】:

我有一列列表对象,开头有一些非空值。假设前 15 个值不为空。

我知道可以将范围的值传递给这样的数组:

Dim mylistObject As ListObject
    Set mylistObject = ThisWorkbook.Sheets("training").ListObjects(1)

Dim theArray() As Variant
   theArray = mylistObject.listcolumn(1).DataBodyRange.value

问题是我怎样才能只传递非空白值。 我知道如何用循环来做,但这里的关键是速度,如果 listobject 有数百行并且操作完成了几十次,那么它花费的时间太长了。

我也知道可以计算非空白单元格的数量并相应地重新调整数组并循环遍历值。还是不够优雅。

有什么想法吗?应该有办法用 VBA 语言来表达

mylistObject.listcolumn(1).DataBodyRange.value
' but not all the range but the non empty ones.

非常感谢

【问题讨论】:

  • 你可以过滤掉空白,复制那个范围并转移到一个数组中。
  • 这很有效。我发现过滤非常不直观。也许我应该改变主意
  • 这可能是一种有用的技术,因此如果您决心避免循环,可能值得克服您的不情愿。
  • 为了艺术:发布了一个迟到但希望有帮助的答案,只是为了向您展示使用 Application.Index 函数的高级功能的替代方法 :-) @Berlines

标签: arrays excel range listobject


【解决方案1】:

使用Application.Index 函数的可能性

演示一种创建和转换列表框列数据数组的简单方法:

  1. 获取原始帖子中已经显示的第一列的所有数据(包括空白)(顺便说一句,数组赋值中的正确语法是theArray = mylistObject.ListColumns(1).DataBodyRange.Value,最后一个“s”在.ListColumns )

  2. 使用 Application.Index 函数的高级功能和从属函数调用 (getNonBlankRowNums()) 消除空白行号

    一行代码的基本转换语法:

   newArray = Application.Index(oldArray, Application.Transpose(RowArray), ColumnArray)

其中 RowArray / ColumnArray 代表(剩余的)行或列 数字的数组。

相关链接:Some peculiarities of the the Application.Index function


Sub NonBlanks()
  ' Note: encourageing to reference a sheet via CodeName instead of Thisworkbook.Worksheets("training")
  '       i.e. change the (Name) property in the VBE properties tool window (F4) for the referenced worksheet
  '       (c.f. https://stackoverflow.com/questions/58507542/set-up-variable-to-refer-to-sheet/58508735#58508735)
    Dim mylistObject As ListObject
    Set mylistObject = training.ListObjects(1)
    
  ' [1] Get data of first column (including blanks)
    Dim theArray As Variant
    theArray = mylistObject.ListColumns(1).DataBodyRange.Value   ' LISTCOLUMNS with final S!!

  ' [2] eliminate blank row numbers
    theArray = Application.Index(theArray, Application.Transpose(getNonBlankRowNums(theArray)), Array(1))

End Sub
Function getNonBlankRowNums(arr, Optional ByVal col = 1) As Variant()
' Purpose: return 1-dim array with remaining non-blank row numbers
  Dim i&, ii&, tmp
  ReDim tmp(1 To UBound(arr))
  For i = 1 To UBound(arr)
      If arr(i, col) <> vbNullString Then   ' check for non-blanks
          ii = ii + 1                       ' increment temporary items counter
          tmp(ii) = i                       ' enter row number
      End If
  Next i
  ReDim Preserve tmp(1 To ii)               ' redim to final size preserving existing items
' return function value (variant array)
  getNonBlankRowNums = tmp
End Function

【讨论】:

    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    相关资源
    最近更新 更多