[英]Stack different cells in one column
I just started learning VBA but I can't really figure this out thing out. 我刚刚开始学习VBA,但我真的无法弄清楚。 I have a column with both positive and negative integers and what I want to do is to take the values that are positive and put them in a new column, and do the same for the negative values.
我有一列同时包含正整数和负整数,我想做的是将正值取到新的列中,并对负值做同样的事情。 I tried making an if-statement but I only know how to shift their spots horizontally, so if I have a positive value in row 1,5,7,22 and 24 they'll appear in these rows in the next column instead of being in row 1,2,3,4 and 5. I did that like this:
我尝试过执行if语句,但是我只知道如何水平移动它们的位置,因此,如果我在行1、5、7、22和24中具有正值,它们将出现在下一行的这些行中,而不是在第1,2,3,4和5行中,我这样做是这样的:
For i = 0 To NoofOb
If Range("D3").Offset(i + 1) > 0 Then
Range("G3").Offset(i) = Range("D3").Offset(i + 1)
ElseIf Range("D3").Offset(i + 1) < 0 Then
Range("J3").Offset(i) = Range("D3").Offset(i + 1)
End If
Next i
Could someone give me a hint or anything? 有人可以给我一个提示吗? I've been looking at this for hours and can't find an answer.
我已经看了几个小时了,找不到答案。 Thanks in advance!
提前致谢!
Try this: 尝试这个:
j = 1
k = 1
For i = 3 To NoofOb
If Range("D" & i).Value > 0 Then
Range("G" & j).Value = Range("D" & i).Value
j = j + 1
ElseIf Range("D" & i).Value < 0 Then
Range("J" & k).Value = Range("D" & i).Value
k = k + 1
End If
Next i
note: I did not test this code and you may need to adjust the starting points of each column ( i
, j
and k
) to suit your needs 注意:我没有测试此代码,您可能需要调整每列的起点(
i
, j
和k
)以适合您的需求
Another option, assuming columns G and J are empty before starting the macro 另一种选择,假设在启动宏之前G和J列为空
For i = 3 To NoofOb
With Range("D" & i) ‘ reference column D current i row
Select Case .Value2 ‘check referenced range value and sct accordingly
Case Is > 0 ‘ if it’s positive
Range("G" & Worksheetfunction.Count(Range("G:G")) + 1.Value2 = .Value2 ‘ fill column G next empty row
Case Is < 0 ‘ if it’s negative
Range("J" & Worksheetfunction.Count(Range("J:J")) + 1.Value2 = .Value2 ‘ fill column J next empty row
End Select
End With
Next
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.