我在查找预设范围内的缺失值时遇到问题。 例如我有:
A 列:3、5、7、9、10、11 我想要返回 VBA 或 excel 中的公式 B 列:1, 2, 4, 6, 8, 12, 13 --> 30
B 列中的最终数字会有所不同。 我希望它根据用户的判断力进行更改。 对于我的问题,我正在处理每月的几天。 因此,一月、二月和三月的总天数不同。 我看过很多示例,但所有示例都基于电子表格中的数组。 如果我想将数组更改为 1-30、1-31 或 1-28(取决于我查看的是哪个月份)怎么办?
这与上面评论中OP引用的公式类似,但针对用户定义的数字数量进行了推广:
=IFERROR(SMALL(IF(ISERROR(MATCH(ROW(A$1:INDEX(A:A,C$2)),D$2:INDEX(D:D,COUNT(D:D)+ROW(D$1)),0)),
ROW(A$1:INDEX(A:A,C$2))),ROW()-ROW(A$1)),"")
必须使用 CtrlShiftEnter
作为数组公式输入编辑
您可以更改公式,以便可以设置起点和终点:
=IFERROR(SMALL(IF(ISERROR(MATCH(ROW(INDEX(A:A,C$2):INDEX(A:A,C$3)),D$2:INDEX(D:D,COUNT(D:D)+ROW(D$1)),0)),
ROW(INDEX(A:A,C$2):INDEX(A:A,C$3))),ROW()-ROW(A$1)),"")
如果 B 列的格式正确,这适用于日期:
这就是 VBA 代码:
Option Explicit
Sub MissingNumbers()
Dim C As Range
Dim LastRow As Long
Dim FirstNumber As Long
Dim LastNumber As Long
Dim i As Long
Dim MyNumbers As New Scripting.Dictionary 'Need Microsoft Scripting Runtime library checked on references
FirstNumber = 1 'here goes your first number to check
LastNumber = 30 'here goes the last number to check
'Assume you have a column A with all the values and column B will hold the missing ones
With ThisWorkbook.Sheets("MySheet") 'Change MySheet for your working sheet name
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'Last Row on column A
'Store your existing numbers in the dictionary
For Each C In .Range("A2:A" & LastRow) 'I'm assuming you have headers on row 1
MyNumbers.Add C.Value, 1
Next C
LastRow = 2 'starting on row 2 for column B
'Loop through all the numbers you want to check
For i = FirstNumber To LastNumber
'If the number doesn't exist on the dictionary
If Not MyNumbers.Exists(i) Then
.Cells(LastRow, 2) = i 'write it on the next available row for columnB
LastRow = LastRow + 1 'add 1 number to last row so we don't overwrite results
End If
Next i
End With
End Sub
你可以尝试:
Option Explicit
Sub test()
Dim LastRowA As Long, LastRowB As Long, i As Long, StartValue As Long, EndValue As Long
Dim rng As Range
StartValue = 1
EndValue = 30
With ThisWorkbook.Worksheets("Sheet1")
LastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A1:A" & LastRowA)
For i = StartValue To EndValue
If Application.WorksheetFunction.CountIf(rng, i) = 0 Then
LastRowB = .Cells(.Rows.Count, "B").End(xlUp).Row
If LastRowB = 1 And .Range("B" & LastRowB).Value = "" Then
.Range("B1").Value = i
Else
.Range("B" & LastRowB + 1).Value = i
End If
End If
Next i
End With
End Sub
结果:
一个可能的公式解决方案将是数组公式:CTRL + SHIFT + ENTER
{=SMALL(IF(COUNTIF(A:A,ROW(INDIRECT("1:"&MAX(A:A)-MIN(A:A)+1))+MIN(A:A)-1)=0,ROW(INDIRECT("1:"&MAX(A:A)-MIN(A:A)+1))+MIN(A:A)-1),ROW())}
向下复制以获取所有值。
我是宏新手.. 如果将上面的宏更改为从范围 A2:J2 水平获取,并且结果缺少范围 L2:U2 星号 0-9 数字中的数字,该怎么办