2015-04-17 125 views
1

我想要使用Excel中的宏從兩個日期中獲取日期差異。在第一個日期的添加應該從sheet1Excel VBA查找日期中兩個日期之間的差異。日期來自不同的工作表

另一個(第二個)日期是從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 
+1

請參閱[如何問一個好問題?](http://stackoverflow.com/help/how-to-ask)。 – segarci

+0

到目前爲止您嘗試了什麼? – progsource

+0

是的,我嘗試了很多方法 –

回答

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 
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 
+0

我不能去「發現日期數」vala邏輯。即使我試過這個code.its給DO上的「運行時錯誤」,而單元格(t,1)行。你可以幫我嗎。? –

+0

這只是爲了確保您不會在Sheet3上粘貼公式。也許你應該上傳文件到評論,如果你不能更好地描述你的數據。 – hc91

+0

我想,我艾雷利用描述寫下了我的問題,我究竟在尋找什麼。讓我知道你是否可以幫助我。 –