Excel VBA范围只有可见的单元格数组

我正在尝试将所有的值从一个范围外的可见单元格中取出到一个数组中。 我的代码只是使数组携带的值,直到第一个不可见的单元格,然后停止。

Public Function ListeMaschinen() As Variant Dim Auswahl As Range With Sheets("qry_TechnischesDatenblatt") Set Auswahl = .Range(.Range("A2:B2"), .Range("A2:B2").End(xlDown)).SpecialCells(xlCellTypeVisible) End With ListeMaschinen = Auswahl End Function 

如果我select范围它显示所有标记我想要得到的细胞。

 Auswahl.Select 

我无法弄清楚为什么,你能帮我吗?

多谢! 背风处

在这里,我已经将范围单元格添加到一个数组。

 Sub examp() Dim rng As Range, cll As Range, i As Integer, a(100) As Variant Set rng = Range(Range("A2:B2"), Range("A2:B2").End(xlDown)).SpecialCells(xlCellTypeVisible) i = 0 For Each cll In rng a(i) = cll.Value i = i + 1 Next End Sub 

在你的代码中,你正在设置一个Variantvariables等于一个Range对象,而不使用Set语句。

以下工作与我做的小testing。 当然,如果你将函数types和其他variables声明为Rangetypes,它也可以工作。

 Option Explicit Sub test() Dim myVar As Variant Set myVar = myList() Debug.Print myVar.Address End Sub Public Function myList() As Variant Dim myRng As Range With Sheets("Sheet1") Set myRng = .Range(.Range("A1:B1"), .Range("A1:B1").End(xlDown)).SpecialCells(xlCellTypeVisible) End With Debug.Print myRng.Address Set myList = myRng End Function 

我认为你的问题是相关的

 .SpecialCells(xlCellTypeVisible) 

当我这样做:

 Public Function ListeMaschinen() As Variant Dim Auswahl As Range With Sheets("qry_TechnischesDatenblatt") Set Auswahl = .Range(.Range("A2:B2"), .Range("A2:B2").End(xlDown)).SpecialCells(xlCellTypeVisible) End With MsgBox Auswahl.Address Set ListeMaschinen = Auswahl 'Auswahl.Select End Function 

我得到一个由两部分组成的Address :可见部分! 在这里输入图像说明

但是当我删除特别的SpecialCells

 Public Function ListeMaschinen() As Variant Dim Auswahl As Range With Sheets("qry_TechnischesDatenblatt") Set Auswahl = .Range(.Range("A2:B2"), .Range("A2:B2").End(xlDown)) End With MsgBox Auswahl.Address Set ListeMaschinen = Auswahl End Function 

我得到一个单一的部分,这也是我使用Select时得到的。

在这里输入图像说明

我testing过了!

 Sub test() Dim myVar As Variant Dim i As Integer i = 0 Set myVar = ListeMaschinen() For Each C In myVar i = i + 1 MsgBox C.Value & C.Address & "-" & i Next End Sub 

除了我之前的评论,这里有一个方法将工作受到一些限制:

你不能有超过65536行的数据; 和你不能有很长的文字(911字符+),或空白可见细胞; 和数据不应该包含string“|〜|”

如果满足这些条件,你可以使用这样的东西:

 Dim v Dim sFormula As String With Selection sFormula = "IF(SUBTOTAL(103,OFFSET(" & .Cells(1).Address(0, 0) & ",row(" & .Address(0, 0) & ")-min(row(" & .Address(0, 0) & ")),1))," & .Address(0, 0) & ",""|~|"")" End With Debug.Print sFormula v = Filter(Application.Transpose(Evaluate(sFormula)), "|~|", False) 

您可以通过更改公式string中的替代文本来使其适应第三个限制。