将Cell.Address保存在数组中,并将其用作单元格公式中的变量

时间:2017-09-20 09:36:53

标签: excel vba

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

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

1 个答案:

答案 0 :(得分:1)

您正在尝试将字符串值分配给整数数组。将Dim myarray() As String更改为Dim rng1 As String, rng2 As Integer, rng3 As Integer将更正第一个错误。

Dim rng1 As String, rng2 As String, rng3 As String应更改为Set rng = Range(rng1, rng2) rng.Select For Each cell In rng.Cells

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

For Each cell In Range(rng1, rng2)

这样就完成了

Do Loop

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

i中,您永远不会增加Loop。这将导致例程无限期地运行或直到Excel崩溃。

这可能与您For i = 2 to 93 Next 打算做的事情相同:

size = size + 1

index = index + 1If .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 正在做多余。您不正确地调整数组大小,留下空值,以后会导致错误:

myarray() demo

let database = {
  foo: {
    bar: {}
  }
}

//changed assignment to argument, since this will fail with invalid left hand assignment.
deepValue(database, "foo/bar/hello", "world");

function deepValue(dbase, stringValue, val)
{
var obj = dbase; //start the chain at base object

//split the string based upon the slashes.
//loop the array with forEach 
stringValue.split("/").forEach(function(value, index, arr){
  
  //if searched value does not exist, create
  if (!obj[value])
  {
    obj[value] = {}; //we use bracket notation, eliminating the need for eval.
  }
  obj = obj[value]; //assign the current property as newest in the chain.
  if (index == arr.length-1 && val)
  {
     obj[value] = val; //if object reaches the end of the chain and there is a val set, assign it. We check the index against the array's length.
  }
}); //array from split

}

console.log(database)