2016-09-09 45 views
0

对不起,我是VBA的新手,因此非常感谢您的帮助! 我正在寻找一些VBA代码,用于查看A列范围内的循环,并且只要A列中的单元格不是0,就用正值替换B列中的相邻单元格,循环遍历范围直到列A中的数据> 0的所有单元在列B中被替换。同样重要的是,列A中的空白单元不覆盖列B中可能存在的正数据。循环替换大于0的值

这就是我在哪里时刻:

Sub Verify() 
    Dim rng As Range 
    Dim i As Long 

    'Set the range in column N 
    Set rng = Range("N2:n1000") 

    For Each cell In rng 
     'test if cell = 0 
     If cell.Value <> 0 Then 
     'write value to adjacent cell 
     cell.Offset(0, -2).Value = *'What do I need here to find the first item of data e.g. N2 in column N?'* 

     End If 
    Next 
End Sub 

非常感谢

+0

您正在阅读N列或A列吗? – Alsatian

+0

您想将Col A的正值复制到Col B,除非Col A中的值为0?我有这个权利吗? – Tyeler

+0

Plase解释评论''我需要在这里找到第一项数据,例如N2列N?'' – Alsatian

回答

0

,我认为它会更容易对付ActiveSheet.Cells为有R天使对象和补偿:

Sub Verify() 

    Dim row As Long 

    For row = 2 To 1000 
     If ActiveSheet.Cells(row,1) <> "" Then ' Not blank 
      If ActiveSheet.Cells(row,1) > 0 Then ' Positive 
       ActiveSheet.Cells(row,2) = ActiveSheet.Cells(row,1) 
      End If 
     End If 
    Next 

End Sub 
0

这是对你开始的内容的编辑。我把范围变成动态的,因为我不喜欢让excel循环比它更长。这是我个人的偏好。第一个代码块将复制任何不为0或空白的东西,任何负数都将由它们的正值代表。至少我是如何理解你的问题的。

而且,这个代码看起来在山口N个数据(如您在代码中有),并将数据复制到山口L.如果你想A到B那么简单地改变rng= ws.Range("A2", ws.Cells(ws.Rows.Count, "A").End(xlUp))myCell.Offset()(0, 1)

Sub Verify() 
    Dim ws As Worksheet 
    Dim rng As Range 

    Set ws = ThisWorkbook.Sheets(1) 'good form to always define the sheet you're working on 
    Set rng = ws.Range("N2", ws.Cells(ws.Rows.Count, "N").End(xlUp)) 'dynamic range 

    For Each myCell In rng 
     If myCell.Value <> "" And myCell.Value <> 0 Then 'If the cell isn't 0 or "" 
      If myCell.Value < 0 Then 'Then if it's negative, make it positive and copy it over 
       myCell.Offset(0, -2).Value = myCell.Value * -1 
      Else: myCell.Offset(0, -2).Value = myCell.Value 'otherwise copy the value over 
      End If 
     End If 
    Next myCell 

End Sub 

如果你只是想拷贝过来是大于0的值,而忽略0的,空白负值,则使用此代码:

Sub Verify() 
    Dim ws As Worksheet 
    Dim rng As Range 

    Set ws = ThisWorkbook.Sheets(1) 'good form to always define the sheet you're working on 
    Set rng = ws.Range("N2", ws.Cells(ws.Rows.Count, "N").End(xlUp)) 'dynamic range 

    For Each myCell In rng 
     If myCell.Value <> "" And myCell.Value > 0 Then 'If the cell is > 0 and not "" 
      myCell.Offset(0, -2).Value = myCell.Value 'copy the value over 
     End If 
    Next myCell 

End Sub 
+0

非常感谢Slai,这个作品完美!因为N中的覆盖值可能是负值,所以我只需将与更改负值相关的行删除,我希望将其复制。再次感谢所有为我的线索做出贡献的人! – eagleboy1234

+0

您的意思是把这个评论放在我的答案上吗?你能标记回答你的问题的答案吗?很高兴我们可以帮助你! – Tyeler

+0

对不起Tyeler,它是为你而设的,尽管Slai的答案也能奏效,但更具有普遍性,而你的答案涵盖了我所要求的所有领域。对困惑感到抱歉! – eagleboy1234

0

如果我正确理解你的问题,你可以在“简化”它是这样的:

Sub Verify() 
    [b2:b1000] = [if(iferror(-a2:a1000,),abs(a2:a1000),b2:b1000&"")] 
End Sub 

只需更换a2:a1000与你列的区域和b2:b1000与B列的范围。