简体   繁体   English

在另一列中打印 if-then 语句的 output

[英]Printing the output of an if-then statement in another column

This sounds like the most simple thing ever but here I am.这听起来像是有史以来最简单的事情,但我在这里。

I have a column with positive and negative numbers.我有一个包含正数和负数的列。 I'm trying to script a code that will print either "P" or "N" in column B (or C or D, doesn't matter) depending on the value of the cell.我正在尝试编写一个代码,根据单元格的值在 B 列(或 C 或 D,无关紧要)中打印“P”或“N”。

For example, if cell A2 has the value -32, then cell B2 should be assigned the string "N".例如,如果单元格 A2 的值为 -32,则应为单元格 B2 分配字符串“N”。 Then goes A3/B3, A4/B4, and so on.然后是 A3/B3、A4/B4,依此类推。

My trouble isn't with the if-then-else stament per se, rather HOW I can get the output to be printed where I want it to be.我的问题不在于 if-then-else 语句本身,而是如何让 output 打印在我想要的位置。

Sub Negatives()
value = Range("A:A")
    If Sgn(value) < 0 Then
        //??? N
    ElseIf Sgn(value) >= 0 Then
        //??? P
    End If
End Sub

Should I be using a for-loop instead to iterate through every value in the column?我是否应该使用 for 循环来遍历列中的每个值?

Short answer yes.简短的回答是。 You could construct an array and stamp it in all at once but that will still require a loop to make decisions on each cell value.您可以构造一个数组并一次性将其全部标记,但这仍然需要一个循环来对每个单元格值做出决定。

I'd suggest:我建议:

Sub Negatives()
    Dim numberRange As Range
    Set numberRange = ThisWorkbook.Sheets("Sheet1").UsedRange.Columns("A")
    
    For Each cell In numberRange.Cells
    
        If cell.Value < 0 Then
            cell.Offset(0, 1).Value = "N"
        ElseIf cell.Value >= 0 Then
            cell.Offset(0, 1).Value = "P"
        End If
    Next
    
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM