VBA集合 – 将值从静态范围读取到集合中

我正试图把一系列的价值观融入一个新的集合中。 范围是固定的,空单元格应该被跳过,内容被添加到集合中的单元格。 但是,我收到一个错误说

“对象variables或块variables未设置”

在线上

"ISINsLX0358 = ThisWorkbook.Sheets("Splits_Vormonat").Range("B3:BK3")" 

有人可以告诉我为什么发生这种情况,并帮助我改进我的代码?

 Dim collLX0358 As New Collection Dim ISINsLX0358 As Range Set collLX0358 = Nothing ISINsLX0358 = ThisWorkbook.Sheets("Splits_Vormonat").Range("B3:BK3") For Each isin In ISINsLX0358 If isin <> "" Then coll.Add isin End If Next isin 

瞧:

 Option Explicit Public Sub TestMe() 'Dim collLX0358 As New Collection - you are not using it, -> you do not need it. Dim ISINsLX0358 As Range Dim isin As Range Dim coll As New Collection 'Set collLX0358 = Nothing - WHY? Set ISINsLX0358 = ThisWorkbook.Sheets(1).Range("B3:BK3") For Each isin In ISINsLX0358 If isin <> "" Then coll.Add isin End If Next isin End Sub 

  • 开始使用Option Explicit
  • Set colLX0358 = Nothing ? 只要你不使用它,从代码中删除它。
  • Range是VBA中的一个对象,应该与Set一起使用