范围对象的VBA特殊方法失败

我已经build立了一个二维数组,并且我想要计算每个块中每个试验的列H中填充单元的数量。 然后,我想将每个试验的最后一行数据旁边填充的单元格数量打印到列T中。

我得到的问题是,当我尝试运行macros时,Excel停止响应,重新启动后,我在标题中收到错误消息。

这里是代码:

Sub dotcountanalysis2() ' create multidimensional array Dim Participant() As Variant Participant = Worksheets("full test").Range("A7", Range("S:S")).Value Dim Block As Variant Block = Columns(2) Dim Trial As Variant Trial = Columns(3) ' define column H as boolean variable Dim Pressed As Boolean Pressed = True ' begin analysis after practice trials For Each Block In Participant For Each Trial In Participant pressedcount = Range("H:H").Cells.SpecialCells(xlCellTypeConstants).Count If Cells(, 8) = Pressed Then Range("T:T").Value = pressedcount End If Next Trial Next Block End Sub 

错误在线:

 pressedcount = Range("H:H").Cells.SpecialCells(xlCellTypeConstants).Count 

我也不能肯定我的语法是正确的,因为我已经尝试进入代码,并且在列H(562)中给出填充单元的总数,并将它打印在每个单元中在列T中。我认为这也是通过我有7011行数据,以最大可能的行数。

这是我的数据的一个样本

最相关的问题可能是你创build了一个巨大的variables数组,然后通过它的值循环两次。

Participant数组包含1048576 * 19 = 19922944个值。 (假设您的工作表中有1048576行)

现在循环访问这些值,并为每个值再循环一次,给出19922944 * 19922944 = 396923697627136次迭代。 所以这就是为什么Excel不响应。

但是,在每次迭代中,您甚至不使用该值…?

如果要计算H列中的Pressed数量并将该数字写入列T,为什么要将列A到S的所有值加载到数组中?

以下是我将在VBA中做的事情

 Dim pressedCount As Long Dim myCell As range Dim pressedRange As range With Worksheets("full test") pressedCount = Application.WorksheetFunction.CountA(.Columns("H")) If pressedCount = 0 Then Exit Sub 'make sure there are cells or else the next line will fail Set pressedRange = .Columns("H").SpecialCells(xlCellTypeConstants) For Each myCell In pressedRange.Cells 'only loop through the cells containing something .Cells(myCell.Row, "T").Value = pressedCount Next myCell End With 

我使用With块,所以我不必在每个范围之前写你的表,因为否则它假定你的意思是活动工作表。 请注意,这假设在H列中除了“按下”之外不能有其他的值,甚至不是头部。 如果有一个标题,从第2行开始,使用.Range(.Cells(2, "H"), .Cells(.Rows.Count, "H"))而不是.Columns("H")

然而,这也可以通过使用公式如=IF($H7="Pressed",COUNTA(H:H),"")