如何在循环中保存单元格地址

时间:2016-06-17 09:05:08

标签: vba loops save location cell

我有一个充满零的电子表格,但有些单元格有值。这些值表示错误,我想知道这些错误的位置。这是我的电子表格:

My spreadsheet

这是我的代码:

Sub FindErrors()

Worksheets("Realisering Flow - aggregeret").Activate

For Each c In Range("EC3:IX1372").Cells
  If c.Value <> 0 Then
    Value = c.Value
    Address = c.Address

    MsgBox "Der er fundet fejl i celle " & Address & _
       "; som har værdien " & Value
  End If

Next

Worksheets("OPS_Volume").Activate

MsgBox "Der er ikke nogen fejl"

End Sub

现在我为每个错误获得了一个msgbox,但是我希望在不同的电子表格中列出所有错误,但我不知道如何在循环中保存地址。另外我想保存Error列的标题。

我希望有人可以帮助我 - 提前谢谢。

1 个答案:

答案 0 :(得分:0)

Sub FindErrors()
Dim myArray() ' declare array as dynamic so we can adjust its size later
ReDim myArray(2,0) ' redim it so it's 2 dimensional
With Worksheets("Realisering Flow - aggregeret")

    For Each c In .Range("EC3:IX1372").Cells
        If c.Value <> 0 Then
            Value = c.Value
            Address = c.Address
            Header = .Cells(1, c.Column).Value

            'MsgBox "Der er fundet fejl i celle " & Address; som har værdien " & Value
            myArray(0, UBound(myArray,2)) = Value
            myArray(1, UBound(myArray,2)) = Address
            myArray(2, UBound(myArray,2)) = Header
            ReDim Preserve myArray(2, UBound(myArray, 2)+1) ' increase size of array by 1
      End If

    Next
End With

Dim Destination As Range
Set Destination = Worksheets("OPS_Volume").Range("A1") ' point Range to A1
' Now push the array into OPS_Volume starting from A1 (adjust Destination as necessary) 
Destination.Resize(UBound(myArray, 2)+1, UBound(myArray, 1)+1).Value = myArray
'MsgBox "Der er ikke nogen fejl"

End Sub

上面的代码将在二维数组中收集您要求的详细信息,然后将该数组输出回Sub中的第二个工作表。你可以很容易地修改它输出数组的位置;让我知道,如果你在这里有什么东西你不明白吗?