我有两个数据报告,我在数据报告1中对数据进行排序,并将其移动到名为" List"的表格中。然后,我完成报告,
我无法在报告中获得其他类型的数据,所以我必须使用一些VBA来解决这个问题。我试过的代码就是这个。
Sub InsertDate()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim i As Integer
Dim RowNr As Long
Dim ActionTitle As String
Dim DaysToExp As Long
Dim ExpDate As Date
Dim Found As Range
Dim FoundRow As Long
Dim Sign As String
Dim Days As String
Dim RowNr2 As Long
ScreenUpdate = False
RowNr = ThisWorkbook.Worksheets("List").Range("A" & Rows.count).End(xlUp).row
RowNr2 = ThisWorkbook.Worksheets("Data2").Range("A" & Rows.count).End(xlUp).row
Set ws1 = ThisWorkbook.Worksheets("List")
Set ws2 = ThisWorkbook.Worksheets("Data2")
ws1.Range("N1").Value = "Expected start date"
For i = 2 To RowNr
ActionTitle = ws1.Range("G" & i).Value
Set Found = ws2.Range("C1:C" & RowNr2).Find(What:=ActionTitle, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows).Activate
FoundRow = ActiveCell.row
Days = ws2.Range("G" & FoundRow).Value
If Days = "" Then
DaysToExp = DaysToExp + 0
ElseIf Left(Days, 1) = "-" Then
Sign = "-"
DaysToExp = Replace(Days, "-", "")
Else
Sign = "+"
DaysToExp = DaysToExp + Days
End If
ExpDate = "=TODAY() & Sign & DaysToExp"
ThisWorkbook.Worksheets("List").Range("N" & i).Value = ExpDate
Next i
ScreenUpdate = True
End Sub
答案 0 :(得分:0)
我已经收紧了一些代码并删除了.Find
来代替工作表函数.Match
。您无需解析 Days 的符号,因为您可以在日期中添加负数。
Sub InsertDate()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim i As Long
Dim RowNr As Long, DaysToExp As Long, FoundRow As Long, RowNr2 As Long
Dim ActionTitle As String, Sign As String, Days As String
Dim ExpDate As Date
Dim Found As Range
Application.ScreenUpdating = False
Set ws1 = ThisWorkbook.Worksheets("List")
Set ws2 = ThisWorkbook.Worksheets("Data2")
RowNr2 = ws2.Range("A" & Rows.Count).End(xlUp).Row
With ws1
RowNr = .Range("A" & Rows.Count).End(xlUp).Row
.Range("N1").Value = "Expected start date"
For i = 2 To RowNr
ActionTitle = ws1.Range("G" & i).Value
If CBool(Application.CountIf(ws2.Range("C1:C" & RowNr2), ActionTitle)) Then
FoundRow = Application.Match(ActionTitle, ws2.Range("C1:C" & RowNr2), 0)
Days = ws2.Range("G" & FoundRow).Value
ExpDate = Date + Days
.Range("N" & i).Value = ExpDate
Else
Debug.Print "missing " & ActionTitle
End If
Next i
End With
Application.ScreenUpdating = True
End Sub
我扔了一个debug.print,如果找不到 ActionTitle ,将报告给VBE的立即窗口。