保存数组中的Cell.Address并将其用作单元格公式中的variables

我有37列x 92行。 一些条件用于分隔产生几个单独范围的每列中的数据。 每个范围内的元素数量都需要计数,所以我使用数组来保存起点地址,并在终点满足的情况下设置一个范围。 然后使用CountIf应用程序在范围内循环。 “myarray(index)= .Cells(i,ncol).Address”行给出运行时错误13types的不匹配。 我应该修改哪一部分? 谢谢。

Option Explicit Sub makeArray() Dim ncol As Integer Dim index As Integer, i As Integer Dim size As Integer Dim rng As Range, cell As Range Dim rng1 As String, rng2 As Integer, rng3 As Integer Dim myarray() As Integer ReDim myarray(size) With ThisWorkbook.Worksheets("sheet2 (2)") For ncol = 2 To 37 size = 1 index = 0 For i = 2 To 93 'assign starting point and save cell.address in array If .Cells(i, ncol) >= 12 And .Cells(i - 1, ncol) <= 12 Then myarray(index) = .Cells(i, ncol).Address size = size + 1 ReDim Preserve myarray(size) index = index + 1 End If Next i i = 2 index = 0 Do While i <> 94 'assign end point and set range using array If .Cells(i, ncol) >= 12 And .Cells(i + 1, ncol) <= 12 Then rng1 = myarray(index) rng2 = .Cells(i, ncol).Address Set rng = Range(rng1, rng2) rng.Select For Each cell In rng.Cells rng3 = .Cells(cell.Row, ncol).Address .Cells(cell.Row, 74 + ncol).Formula = " =CountIf(" & rng1 & ":" & rng3 & "," & rng3 & ")" Next cell index = index + 1 End If Loop Next ncol End With End Sub 

您正试图将一个string值分配给一个整数数组。 将Dim myarray() As Integer更改为Dim myarray() As String将更正第一个错误。

Dim rng1 As String, rng2 As Integer, rng3 As Integer should be changed to Dim rng1 As String, rng2 As String, rng3 As String

除非绝对必要,否则不要使用select。

 Set rng = Range(rng1, rng2) rng.Select For Each cell In rng.Cells 

然后这就完成了

 For Each cell In Range(rng1, rng2) 

迭代特定范围时不要使用循环。

在你的Do Loop你从来没有增加过i 。 这将导致例程无限期运行或直到Excel崩溃。

这可能会做你的Loop所要做的相同的事情:

 For i = 2 to 93 Next 

size = size + 1index = index + 1正在做冗余。 您不正确地调整您的数组的大小留下空的值,这将导致稍后的错误:

myarray()演示

 If .Cells(i, ncol) >= 12 And .Cells(i - 1, ncol) <= 12 Then index = UBound(myarray) If myarray(index) <> "" Then index = index + 1 ReDim Preserve myarray(index) End If myarray(index) = .Cells(i, ncol).Address End If