在Excel中循环遍历数组

时间:2019-07-10 13:40:17

标签: excel vba loops

尝试循环工作表“数据”。范围为“ AM1:AS12”,并将数据复制到从BD1开始的范围,只要数据不等于“#N / A”

我的代码可用于复制第一列,但此后对数据不执行任何操作。我要去哪里错了?

Set S2 = Sheets("data").Range("AM:AM")
Set S3 = Sheets("data").Range("BD:BD")

Dim i As Integer, j As Integer 

j = 1
For i = 1 To 12 

   If S2.Cells(i, 1).Value <> "#N/A" Then 
      S3.Cells(j, 2).Value = S2.Cells(i, 1).Value 
      j = j + 1 
   End If

Next i 

3 个答案:

答案 0 :(得分:1)

替换:

<> "#N/A"

通过:

Not(Application.WorksheetFunction.IfNa(...))

答案 1 :(得分:1)

这在我测试时有效。

    Sub CopyCell()

    Set S2 = Sheets("data").Range("A:A")
    Set S3 = Sheets("data").Range("M:M")

    Dim i As Integer, j As Integer

    For j = 1 To 2
    For i = 1 To 12

       If S2.Cells(i, j).Value <> "#N/A" Then
          S3.Cells(i, j).Value = S2.Cells(i, j).Value

       End If

    Next i
    Next j

    Call DeleteBlank

    End Sub



Sub DeleteBlank()

Dim x As Integer
Dim y As Integer

For y = 13 To 16 'Range numbers for the columns the data is copied to
For x = 1 To 10  ' Number of cells of data you want to loop through

If Cells(x, y).Value = "" Then
Cells(x, y).Delete Shift:=xlUp

End If

Next x
Next y

End Sub

答案 2 :(得分:0)

最好的办法是不检查它是否等于“#N / A” 最好是检查它是否是错误:如果不是(IsError(S2.Cells(i,1).Value))然后