搜索一系列文本(如果找到),将单元格复制到电子表格的另一部分

时间:2014-03-17 14:37:02

标签: excel excel-vba sorting copy vba

我是制作excel宏的新手,所以不确定如何对此进行编码。基本上,在运行中,我想搜索一系列单元格(在这种情况下,A2-A25)某些数字范围(如1700-1799,2900-2999),如果找到,则在另一个地方复制/排序电子表格。

例如,工作表(运行后)看起来像这样:
1712
2983
2931
1723
1745

1712
1723
1745

2983
2931

像这样的宏可能吗?

2 个答案:

答案 0 :(得分:2)

这会将结果放在 B C 列中:

Sub GetValues()
    Dim A As Range, r As Range
    Dim i As Long, j As Long
    Dim v As Long
    Set A = Range("A2:A25")
    i = 1
    j = 1
    For Each r In A
        v = r.Value
        If v >= 1700 And v <= 1799 Then
            Cells(i, "B").Value = v
            i = i + 1
        End If
        If v >= 2900 And v <= 2999 Then
            Cells(j, "C").Value = v
            j = j + 1
        End If
    Next r
End Sub

修改#1

此版本将结果存储在第30行第50行中的 A 列中......... ........修改以满足您的需求:

Sub GetValues()
    Dim A As Range, r As Range
    Dim i As Long, j As Long
    Dim v As Long
    Set A = Range("A2:A25")
    i = 30
    j = 50
    For Each r In A
        v = r.Value
        If v >= 1700 And v <= 1799 Then
            Cells(i, "A").Value = v
            i = i + 1
        End If
        If v >= 2900 And v <= 2999 Then
            Cells(j, "A").Value = v
            j = j + 1
        End If
    Next r
End Sub

修改#2

此版本复制整行:

Sub GetValues()
    Dim A As Range, r As Range
    Dim i As Long, j As Long
    Dim v As Long
    Set A = Range("A2:A25")
    i = 30
    j = 50
    For Each r In A
        v = r.Value
        If v >= 1700 And v <= 1799 Then
            r.EntireRow.Copy Cells(i, "A")
            i = i + 1
        End If
        If v >= 2900 And v <= 2999 Then
            r.EntireRow.Copy Cells(j, "A")
            j = j + 1
        End If
    Next r
End Sub

答案 1 :(得分:0)

您不需要宏,您可以使用此数组公式:

=SMALL(IF(($A$1:$A$25>=1700)*($A$1:$A$25<=1799);$A$1:$A$25;"");ROW(A1))

例如在c1中写入,然后向下复制以获取所有值。

您需要按Ctrl Shift Enter输入公式

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