VBA for循环;如果单元格在范围内,则插入范围值

时间:2014-04-08 16:40:16

标签: excel vba excel-vba

我正在努力努力使这项工作。我有一个美元金额列表,我需要遍历它们并识别那些属于某个范围的数据。

当前数据

Name      Value     Range     
Bob       $1403
Julius    $11,425
Mike      $20,493
Lucas     $9,970

所需输出

Name     Value     Range    
Bob      $1403     <$10,000
Julius   $11,425   $10,000-$50,000
Mike     $20,493   $10,000-$50,000
Lucas    $9,970    <$10,000

当前结果

Name     Value     <$10,000    
Bob      $1403     <$10,000
Julius   $11,425  
Mike     $20,493   
Lucas    $9,970    

当前代码

Sub FindMatchingValue()
 Dim assetRange As Range
 Set assetRange = Range("B2:B5")
 Set nextRange = Range("C2:C5")
 For Each c In Worksheets("Single Audit").Range("B2:B5").Cells
    If c(i, 1).Value <= 10000 Then
        nextRange(c).Value = "<$10,000"
   Else
   If (c(i, 1).Value >= 10000) And (c(i, 1).Value <= 50000) Then
        nextRange(c).Value = "$10,000-$50,000"
    End If
    End If
  Next c
End Sub

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

版本较短:

Sub FindMatchingValue()
    With Worksheets("Single Audit").Range("C2:C5")
        .Formula = "=IF(B2<10000,""<$10,000"",IF(AND(B2>10000,B2<=50000),""$10,000-$50,000"",""""))"
        .Value = .Value
    End With
End Sub

以上代码使用公式查找结果,.Value = .Value使用thouse结果重写公式。

或者,如果您想修改代码:

Sub FindMatchingValue2()
    Dim assetRange As Range
    Dim c As Range

    Set assetRange = Worksheets("Single Audit").Range("B2:B5")

    For Each c In assetRange
        If c.Value <= 10000 Then
            c.Offset(, 1).Value = "<$10,000"
        ElseIf (c.Value >= 10000) And (c.Value <= 50000) Then
            c.Offset(, 1).Value = "$10,000-$50,000"
        End If
    Next c
End Sub

答案 1 :(得分:0)

为什么VBA会做这么简单的任务?

假设值从B2开始,请写下公式:

=LOOKUP(B2;{0;10000;50000.01};{"<$10,000";"$10,000-$50,000";">$50,000"})

并复制

根据您的区域设置,您可能需要更换arg separator&#34;;&#34; by&#34;,&#34;