如何从范围中获取所有值

时间:2014-11-03 22:40:06

标签: excel excel-vba excel-formula excel-2007 vba

我有一个列(缺少col),它从我的id列中获取所有缺少的数字。因此,从整个单元格范围来看,大多数都是空的,我想制作另一列非空的值 - 主要是因为有数千或者行,我需要在顶部看到这些数字。我没有看到连续丢失的两个,但这会使逗号分隔的id单元格 - 即PW140000024,PW140000025 - 可能需要在某个时刻处理。

使得缺少col的功能:

=IF(MID(E2,3,99)-MID(E1,3,99)>2,"PW"&MID(E1,3,99)+1&",PW"&MID(E2,3,99)-1,IF(MID(E2,3,99)-MID(E1,3,99)>1,"PW"&MID(E1,3,99)+1,""))

示例:

id column   | missing col             | missing without empty rows
PW140000023 |                         | PW140000024
PW140000025 | PW140000024             | PW140000027
PW140000026 | PW140000027             | PW140000029
PW140000028 | PW140000029,PW140000030 | PW140000030
PW140000031 |                         |
PW140000032 |                         |

由于

2 个答案:

答案 0 :(得分:3)

假设您的数据看起来像第1行中的标题行而您的数据从第2行开始,则id列是E列,您希望“Missing”列为F列:

tigeravatar example

在单元格F2中,向下复制是这个公式:

=IFERROR("PW"&INDEX(SUBSTITUTE($E$2,"PW","")+ROW(INDIRECT("1:"&MAX(INDEX(--(SUBSTITUTE($E$2:$E$7,"PW","")),))-SUBSTITUTE($E$2,"PW","")+1))-1,
    MATCH(1,
        INDEX(
            (COUNTIF(F$1:F1,"*"&INDEX(SUBSTITUTE($E$2,"PW","")+ROW(INDIRECT("1:"&MAX(INDEX(--(SUBSTITUTE($E$2:$E$7,"PW","")),))-SUBSTITUTE($E$2,"PW","")+1))-1,))=0)
             *
            (COUNTIF($E$2:$E$7,"*"&INDEX(SUBSTITUTE($E$2,"PW","")+ROW(INDIRECT("1:"&MAX(INDEX(--(SUBSTITUTE($E$2:$E$7,"PW","")),))-SUBSTITUTE($E$2,"PW","")+1))-1,))=0)
        ,)
    ,0))
,"")

该公式适用于此类示例的小型数据集,但我可以看到它如何开始大幅度减慢Excel的大数据集。由于这种复杂性,我建议创建一个VBA子例程来为您获取结果。

这样的事情应该有效:

Sub tgr()

    Const strIDcol As String = "E"  'Change to the actual column containing the id's
    Const strOPcol As String = "F"  'Change to the actual column you want to OutPut results to
    Const lStartRow As Long = 2     'Change to the row your data actually starts on (NOT the header row)

    Dim ws As Worksheet
    Dim rngIDs As Range
    Dim IDCell As Range
    Dim arrMissing() As String
    Dim MissingIndex As Long
    Dim IDMin As Long
    Dim IDMax As Long
    Dim i As Long

    Set ws = ActiveWorkbook.ActiveSheet 'Assuming we're working with the active workbook and active worksheet
    Set rngIDs = Range(strIDcol & lStartRow, ws.Cells(Rows.Count, strIDcol).End(xlUp))

    IDMin = Val(Replace(rngIDs.Cells(1).Value, "PW", vbNullString))
    IDMax = Val(Replace(rngIDs.Cells(rngIDs.Cells.Count).Value, "PW", vbNullString))

    ReDim arrMissing(1 To IDMax - IDMin + 1 - rngIDs.Cells.Count, 1 To 1)

    For i = IDMin To IDMax
        If WorksheetFunction.CountIf(Columns(strIDcol), "*" & i) = 0 Then
            MissingIndex = MissingIndex + 1
            arrMissing(MissingIndex, 1) = "PW" & i
        End If
    Next i

    Range(strOPcol & lStartRow).Resize(MissingIndex).Value = arrMissing

End Sub

答案 1 :(得分:0)

通过创建一个以PW140000023开头的ID列表(比如Row1中的="PW"&140000022+row()),将这些与id column相匹配(比如=MATCH(A1,Sheet1!A:A,0)复制到适合的,将这些结果修改为值,然后过滤以删除匹配的数字结果。