wk2LastRow = wk2.Cells(Rows.Count, 1).End(xlUp).Row
i = 2
For wk2Range = 2 To wk2LastRow
id = wk2.Cells(wk2Range, 1)
Set f = wk1.Range("A2:I7").Find(id, , xlValues, xlPart)
'Conditional Statement code to be inserted here
Next wk2Range
背景资料:
我想将值列表与“A2:I7”(1到6)匹配。我需要从表中获得的数据是第二个OFF日期的日期。例如,对于名称2,第二个关闭日期是01/02 / 15,01 / 06/15。
我希望代码找到匹配项,然后水平读取代码以找到第二天,然后结束(xlup)以获取日期。
我已经想到了4种可能的场景,但我不确定如何将它们写入代码。我只需要第二天的日期,代码可以忽略其余的变化。
请参阅图片进行详细说明:
答案 0 :(得分:0)
这不是最优雅的解决方案,但应该返回您希望的日期:
Private Sub ViewHolidayDates()
'Defined rota range:
Set Rota = Sheet1.Range("B2:I7").Cells
'How many dates across.
Dim RowLength As Integer: RowLength = 8
'Which Name we are looping.
Dim Row As Integer: Row = 1
'Where within the range loop we are.
Dim UserRecord As Integer: UserRecord = 0
'Current count of "off" for current Row.
Dim Holiday As Integer: Holiday = 0
Dim DateValue As String
For Each Record In Rota
If Record = "off" Then
Holiday = Holiday + 1
If Holiday = 2 Then
DateValue = Sheet1.Range("B2").Offset(-1, UserRecord).Value
MsgBox (DateValue)
'reset Holiday counter:
Holiday = 0
End If
End If
UserRecord = UserRecord + 1
If UserRecord = RowLength Then
'Reset counters ready for new "Name"
Row = Row + 1
UserRecord = 0
Holiday = 0
End If
Next Record
End Sub
请将我的代码中的Rota
变量设置为Excel表格中的范围,并将代码中的Sheet1.Range("B2")
设置为您范围内的第一个记录。
<强>更新强>
您可以将RowLength
和If Holiday = 2
调整为更适合您的方案的值。您还应该注意"off"
区分大小写。
<强>更新强>
我已更新Holiday
计数器以在IF
语句中重置,然后会返回第二个&#34; off&#34;的每个实例的日期。
此外,我的Row - Row - 1
不是必需的,因为我定义的范围已修复:Sheet1.Range("B2")
我们只需要说Offset(-1, UserRecord)
并动态传递我们期望日期的列数是。
答案 1 :(得分:0)
这是一种方法,只需将SecondOff分配给您在主调子中选择的范围。请注意,与Find相比,可能有更好的方法,但我希望与您的问题保持同步。
Public Function SecondOff(Schedule As Range) As Variant
Dim rw As Range, Temp As Variant
Dim i As Integer, j As Integer
Dim wrow As Integer, firstI As Integer, origI As Integer
ReDim Temp(1 To 6, 1 To 9)
For Each rw In Schedule.Range("2:" & Schedule.Rows.Count).Rows
i = 1
j = 2
wrow = rw.Cells(1, 1)
Temp(wrow, 1) = wrow
If (rw.Find("off", rw.Cells(1, i), xlValues, xlPart) Is Nothing) Then
Temp(wrow, 2) = "None"
Else
origI = rw.Find("off", rw.Cells(1, i), xlValues, xlPart).Column
Do
firstI = rw.Find("off", rw.Cells(1, i), xlValues, xlPart).Column
If firstI <= origI And j > 2 Then Exit Do
i = rw.Find("off", rw.Cells(1, firstI), xlValues, xlPart).Column
If i <= origI Then Exit Do
If i - firstI = 1 Then
Temp(wrow, j) = Schedule(1, i)
j = j + 1
Else
i = firstI
End If
Loop Until j > 8
End If
Next rw
SecondOff = Temp
End Function