[英]Excel VBA to find out difference between two dates in days. where dates come from different sheets
我想使用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
不確定您的意思是什么,但可能僅僅是這個(這取決於您的日期在Sheet1
和Sheet2
。我假設它們在第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
解決方法如下:-
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.