Excel VBA查找两个日期之间的差异。日期来自不同的床单

时间:2015-04-17 07:11:29

标签: excel vba excel-vba

我希望使用Excel中的宏从两个日期获取日期差异。第一个日期的添加应该来自sheet1

另一个(第二个)日期来自sheet2,它们的输出(天差)我们必须在Excel sheet3中显示。

我试过了:

 Dim i As Range,j As Range, ifind As Range, y,z, dest As Range, jfind As Range
 On Error Resume Next
 Worksheets("sheet3").Cells.Clear
 With Worksheets("sheet1")
 .UsedRange.Copy Worksheets("sheet3").Range("a1")
 For Each i In Range(.Range("D2"), .Range("D2").End(xlDown))
 y=i.value
 With Worksheets("sheet1")
 Set ifind = .Cells.Find(what:=y, lookat:=ylWhole)
 For Each j In Range(.Range("D2"), .Range("D2").End(xlDown))
 z=j.value
 With Worksheets("sheet2")
 Set jfind = .Cells.Find(what:=z, lookat:=zlWhole)
 If ifind and jfind Is Nothing Then GoTo line1
 set datefind="datedif("ifind","jfind","d")" .Copy
 With Worksheets("sheet3")
 End with 'sheet2
 end with 'sheet2
 line1:
 Next
 end with 'sheet1
 Application.CutCopyMode = False

2 个答案:

答案 0 :(得分:0)

不确定您的意思,但它可能就是这个(取决于您的日期在Sheet1Sheet2中的位置。我认为它们在第1列中下降):

Sub Days()
'Count Number of Dates in "Sheet1"
Sheets("Sheet1").Select
NumberDates = 0
t = 1
Do While Cells(t, 1)
    t = t + 1
Loop
NumberDates = t - 1

'Place Formula for date difference in Sheet3
Sheets("Sheet3").Select
With ActiveSheet.Range(Cells(1, 1), Cells(t, 1))
    .Formula = "=DAYS(Sheet2!A1,Sheet1!A1)"
End With
End Sub

答案 1 :(得分:0)

以下是解决方案: -

Private Sub CommandButton1_Click()
Dim currDate As Date
Dim dateOffset As Integer
Dim count1 As Integer
Dim str As String
Dim cuntfinal As Integer
Dim strfinal As String
countfinal = 2
 count1 = 2
 count0 = 2
 strdate = "d" & CStr(count0)
For Each cell In Range(Sheet3.Range(strdate), Sheet3.Range(strdate).End(xlDown))
 strdate = "d" & CStr(count0)
 count0 = count0 + 1
 If cell Is Nothing Then GoTo line10
  startDate = Sheets("Sheet3").Range(strdate)
  str = "h" & CStr(count1)
 For Each cell1 In Range(Sheet3.Range(str), Sheet3.Range(str).End(xlDown))
  count1 = count1 + 1
  GoTo line20
  Next cell1
line20:
 If cell1 Is Nothing Then GoTo line10
currDate = Sheets("Sheet3").Range(str)
If currDate = "12:00:00 AM" Then GoTo line40

dateOffset = DateDiff("d", startDate, currDate)
line30:
strfinal = "j" & CStr(countfinal)
Sheets("Sheet3").Range(strfinal) = dateOffset
countfinal = countfinal + 1
line10:
Next cell
line40:
strfinal = "j" & CStr(countfinal)
Sheets("Sheet3").Range(strfinal) = " "
countfinal = countfinal + 1
 GoTo line10
  End Sub