我正在尝试在Word中创建一个从Excel电子表格中拖动数据的报表。在工作PC上我对我能做什么有限(不能从excel宏中打开单词)所以我的解决方法是将我需要的所有信息从一个excel工作表复制到另一个excel工作表中,以便格式正确/被安排作为单词邮件合并的数据源。
我遇到的问题是我要复制一天07:00到下一次07:00之间运行的记录。当我为时间添加嵌套IF时,它有点错误。
非常感谢任何帮助, Rgds Iain
Sub CopyFromLog()
Dim LastRow As Long
Dim i As Long, j As Long, ns As Date, nf As Date, o As Date, f As String, s As String, t As Date
With Worksheets("Log")
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
With Worksheets("Data")
Worksheets("Data").Rows("3:" & LastRow).Clear
j = .Cells(.Rows.Count, "B").End(xlUp).Row + 2
End With
With Worksheets("Navigation")
ns = Worksheets("Navigation").Cells(3, "C").Value ' the report start date
nf = Worksheets("Navigation").Cells(4, "C").Value ' the report end date
End With
For i = 2 To LastRow
With Worksheets("Log")
o = Worksheets("Log").Cells(i, "B").Value 'start date
t = Worksheets("Log").Cells(i, "V").Value 'end date
s = Worksheets("Log").Cells(i, "R").Value 'start time
f = Worksheets("Log").Cells(i, "W").Value 'finish time
If o <= ns And s >= "07:00" Then
If t >= nf And f <= "07:00" Or t >= nf And f <= "R" Then
.Rows(i).Copy Destination:=Worksheets("Data").Range("A" & j)
j = j + 1
End If
End If
End With
Next i
End Sub`
答案 0 :(得分:0)
这是对您的程序的轻微重写。请参阅个别观察的评论。
Sub CopyFromLog()
Dim LastRow As Long, i As Long, j As Long
Dim ns As Date, nf As Date, o As Date, t As Date
Dim f As String, s As String
With Worksheets("Log")
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
With Worksheets("Data")
' You realize that LastRow was just defined as the last row on the Log workbook
' and you are now using it on the Data worksheet to clear rows
.Rows("3:" & LastRow).Clear
'I don;t understand this next line. You just cleared everthing from row 3 down so j should be 2
j = .Cells(.Rows.Count, "B").End(xlUp).Row + 2
End With
With Worksheets("Navigation")
ns = .Cells(3, "C").Value + TimeSerial(7, 0, 0) ' the report start dateTIME
nf = ns + 1 '24 hours later
End With
With Worksheets("Log")
For i = 2 To LastRow
o = .Cells(i, "B").Value + CDate(.Cells(i, "R").Value) 'start dateTIME
t = .Cells(i, "V").Value + CDate(.Cells(i, "W").Value) 'end dateTIME
'I couldn't figure out your logic so I made my own.
'Yours looked backwards and you were comparing f to the leffter "R" (f was never assigned a value either)
If o >= ns And t < nf Then
.Rows(i).Copy Destination:=Worksheets("Data").Range("A" & j)
j = j + 1
End If
Next i
End With
End Sub
最大的区别在于,我已经放弃了尝试通过比较看起来像时间的字符串并尝试将时间带回日期以便 ns var将尝试获得正确答案的概念。类似于07/30/2016 07:00
我对所有其他日期时间采用了类似的方法,以便可以进行直接比较。