2015-04-17 72 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

我想,我艾雷利用描述写下了我的问题,我究竟在寻找什么。让我知道你是否可以帮助我。 –