我正在用vba开发工作簿;工作表中可以包含不同数量的命名“ CheckCells”,它们充当“布尔”下拉列表(“是” /“否”)来操作同一工作表中的其他单元格。
我正在尝试开发可在单元格公式中调用的Public Function宏。它的目的是将所有这些CheckCell都“折叠”为单个Long型输出-输出将等于我从工作簿中的特殊“归档”工作表中读取的列索引; “存档”工作表将作为某些值的永久“内存”,因为它们对于工作簿功能至关重要,但是在工作簿打开/关闭时会丢失。
以下是我需要帮助的代码的简化版本。如Debug.Print行中指出的那样,似乎我尝试以任何方式使Range型变量变暗,然后将其设置为等于单元格范围,大多数尝试使用该变量的对象属性进行读取的尝试都会抛出错误结果,例如“无法获取属性...”,“对象定义的错误...”或“应用程序定义的错误...”。实际上,“ VersionCheckCell”是ActiveSheet的命名单元。
Public Function CollapseRun() As Long
Dim ActSht As Worksheet
Set ActSht = ThisWorkbook.ActiveSheet
'Variables to get the range of cells to loop through when finding VersionCount.
Dim intVisRows As Long: intVisRows = 1
Dim intVisCols As Long: intVisCols = 1
'[Code to evaluate inVisCols and intVisRows omitted to shorten post...]
Dim EndCell As Range
Set EndCell = ActSht.Cells(intVisRows, intVisCols)
'Debug.Print [VersionCheckCell].Name.Name 'This works. If explicitly giving valid ranges, _
I can read its properties like normal.
'Debug.Print EndCell.Name.Name 'This fails. When I define a _
Range variable, then Set it as some cells, I can't read its object properties.
Dim VisibleRange As Range
Set VisibleRange = ActSht.Range(ActSht.Cells(1, 1), EndCell) 'Cell Range to
loop through.
Dim intCzCells As Integer: intCzCells = 0
Dim Cell As Range
Dim arrCz() As Variant
'This is the Application-defined error-throwing loop.
For Each Cell In VisibleRange
If InStr(Cell.Name.Name, "CheckCell") <> 0 Then 'Checks cell's name for "CheckCell".
intCzCells = intCzCells + 1
arrCz(intCzCells) = Cell.Address 'Storing addresses to later check values.
End If
Next Cell
'[More code after this loop to determine CollapseRun value...]
我在询问之前进行了研究,并发现了许多其他带有标签的问题,例如“执行时出现应用程序定义的错误”等。许多此类问题/解决方案源于质量检查人员未正确设置要抛出的变量读取时出错。我已经盯着代码修改了几个小时,无法弄清楚我可能如何不正确地设置VisibleRange或EndCell变量,因此我倾向于相信其他错误,但是我希望这里有人我朝着正确的方向前进。
我在Windows 10上使用Excel 2016。
(编辑:插入intCzCells初始化为0的代码的缺失部分。
(编辑2:修正了注释中指出的不必要的范围评估。)
答案 0 :(得分:1)
约翰·科尔曼(John Coleman)在评论中指出的主要问题是,如果范围不是 named 单元格,.Name.Name
将引发错误。
解决此问题的一种方法是在循环中使用变通方法错误处理(我还修复了将代码实际正确添加到数组的代码)。
For Each Cell In VisibleRange
On Error GoTo NoName
If InStr(Cell.Name.Name, "CheckCell") <> 0 Then
intCzCells = intCzCells + 1
ReDim Preserve arrCz(intCzCells - 1) 'Array indexed from 0.
arrCz(intCzCells - 1) = Cell.Address
End If
NoName:
Resume NextIteration
NextIteration:
Next Cell