抱歉,我是VBA的新手,所以感谢任何帮助! 我正在寻找一个VBA代码用于查看A列范围的循环,只要A列中的单元格不为0,用正值替换B列中的相邻单元格,循环遍历该范围直到所有具有数据的单元> A列中的0已在B列中替换。A列中的空白单元格不会覆盖B列中可能存在的正数据。
这就是我现在所处的位置:
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 :(得分:0)
我认为与Range对象和偏移一样处理ActiveSheet.Cells会更容易:
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
答案 1 :(得分:0)
这是您开始编辑的内容。我使范围变得动态,因为我不喜欢使excel循环比它更长。这是我个人的偏好。第一个代码块将复制任何非0或空白的内容,任何负数将由其正对应项表示。这至少是我理解你的问题的方式。
此外,此代码查看Col N中的数据(就像您在代码中一样)并将数据复制到Col 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
答案 2 :(得分:0)
如果我理解你的问题,你可以简化&#34;它是这样的:
Sub Verify()
[b2:b1000] = [if(iferror(-a2:a1000,),abs(a2:a1000),b2:b1000&"")]
End Sub
只需将a2:a1000
替换为您的A列范围,将b2:b1000
替换为B列范围。