在以上列中,我有唯一的日期。
我有一个下拉列表,在这里可以选择任何内容..所以它有8个排列(2 ^ 3)..所以我想根据选择内容提取可能的日期。假设我选择Year为2020,day为19,我将提取与两个条件都匹配的可能日期。
现在我正在使用8 if elseif-= ... end if statement ... and for loop ..还有其他方法可以完成相同的工作吗?我想编写一个函数,该函数将(天,月,年,最后一行)作为参数,并根据可能的日期进行计算。有人可以给我任何想法吗?
我的代码现在:
Public Sub ProbableDate(CaseNo As Integer, lastrow As Long)
Dim sh As Worksheet, sh1 As Worksheet
Set sh1 = Worksheets("Dashboard")
Set sh = Worksheets("Logical operation")
Dim Y As String, M As String, D As String
Y = sh1.Cells(4, 1).Value
M = sh1.Cells(4, 2).Value
D = sh1.Cells(4, 3).Value
Dim L As Long, i As Long
L = 2
With sh
.Range("H2:H1048576").Clear
For i = 2 To lastrow
Select Case CaseNo
Case 1
If Year(.Cells(i, 2).Value) = Y Then
.Cells(L, 8).Value = .Cells(i, 2).Value
L = L + 1
End If
Case 2
If MonthName(Month(.Cells(i, 2).Value)) = M Then
.Cells(L, 8).Value = .Cells(i, 2).Value
L = L + 1
End If
Case 3
If Day(.Cells(i, 2).Value) = D Then
.Cells(L, 8).Value = .Cells(i, 2).Value
L = L + 1
End If
Case 4
If Year(.Cells(i, 2).Value) = Y And MonthName(Month(.Cells(i, 2).Value)) = M Then
.Cells(L, 8).Value = .Cells(i, 2).Value
L = L + 1
End If
Case 5
If Year(.Cells(i, 2).Value) = Y And Day(.Cells(i, 2).Value) = D Then
.Cells(L, 8).Value = .Cells(i, 2).Value
L = L + 1
End If
Case 6
If Day(.Cells(i, 2).Value) = D And MonthName(Month(.Cells(i, 2).Value)) = M Then
.Cells(L, 8).Value = .Cells(i, 2).Value
L = L + 1
End If
Case 7
If Day(.Cells(i, 2).Value) = D And MonthName(Month(.Cells(i, 2).Value)) = M And Year(.Cells(i, 2).Value) = Y Then
.Cells(L, 8).Value = .Cells(i, 2).Value
L = L + 1
End If
Case Else
MsgBox "Wrong Info"
End Select
Next i
End With
End Sub
You can simplify your code using a binary lookup table. Each CaseNo
matches with a particular set of true/false outcomes for the day, month and year check. These are different to your original mapping, here is the new map:
CaseNo DMY 0 fail 1 D 2 M 3 DM 4 Y 5 D Y 6 MY 7 DMY
And the code:
With sh
.Range("H:H").Clear
For i = 2 To lastrow
OK = 0
If Day(.Cells(i, 2).Value) = D Then OK = OK + 1
If MonthName(Month(.Cells(i, 2).Value)) = M Then OK = OK + 2
If Year(.Cells(i, 2).Value) = Y Then OK = OK + 4
If OK = CaseNo Then
.Cells(L, 8).Value = .Cells(i, 2).Value
L = L + 1
Else
MsgBox "Wrong Info"
End If
Next i
End With
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句