用vba清理excel表

我有一个有很多数据的Excel表。 你可能知道,这有很多问题。 一个主要的问题是数据太多。 我不熟悉vba,但我想知道如何清理数据。

我有一个有3个字段的表:date,时间和温度。 温度以分钟为单位logging。 温度只logging从上午7时至晚上10时,但表是在24小时的基础上。 所以我的表格有很多空白的单元格。 所以,我想写一个代码,指出:

if ((time < 7am) or (time > 10pm)): delete row 

我可以这样做吗?

而且,另一个问题是数据不是在周末收集的。 我没有给出一天的字段,只有这种格式的date字段:20130102这是2013年1月2日。我想:

 if ((date = saturday) or (date = sunday)): delete row 

这些都是可行的吗?

我的床单如下所示:

A ………….. B ……… …. C

date……..时间………温度

在这里输入图像说明

由于您的date和时间格式与正常情况不同,因此我们需要操纵这些值以获取要testing的内容。 考虑下面的例子(我已经评论了每一行以帮助你继续):

 Sub DeleteRows() Dim lastRow As Long Dim Cell As Long Dim dt As Date 'Work with the active sheet. With ActiveSheet 'Find the last row of your dataset. lastRow = .Range("A:A").Find("*", searchdirection:=xlPrevious).Row 'Format your time column to a readable time. .Columns("B").NumberFormat = "[$-F400]h:mm:ss AM/PM" 'Loop through the rows, beginning at the bottom. For Cell = lastRow To 2 Step -1 'Piece together the date. dt = Mid(.Cells(Cell, 1), 7, 2) & "/" & _ Mid(.Cells(Cell, 1), 5, 2) & "/" & Left(.Cells(Cell, 1), 4) 'If the date is a Sat or Sun, delete the row. If Weekday(dt) = 1 Or Weekday(dt) = 7 Then .Rows(Cell).EntireRow.Delete 'If the time is before 7am or after 10pm, delete the row. ElseIf Hour(.Cells(Cell, 1)) < 7 Or Hour(.Cells(Cell, 1)) > 22 Then .Rows(Cell).EntireRow.Delete End If Next Cell End With MsgBox "Done!" End Sub 

关于代码的一些事情要注意。 首先,我们必须从列表的底部开始,因为当我们删除行时,其余的行向上移动。 如果我们要从上到下(例如A1A10 ),如果我们删除第5行,第6行将滑入它的位置,并且循环将跳过第5行(先前第6行)并继续到第6行。换句话说,当删除行时从上到下循环将最终无意中跳过行。

其次,我不得不猜测你的时间格式。 虽然我相信我猜对了,但我可能没有。 如果我错了,并且我的代码不能将时间列更改为可读的时间,请logging一个macros,同时更改该列的格式,并用我的新格式( "[$-F400]h:mm:ss AM/PM" )。

最后,由于您的date列是exception格式(对于Excel),我们需要重新排列date以便Excel可以读取它。 一旦我们这样做了,我们可以使用结果date来查看date是否是星期六。 或太阳。

你可以这样做,假定包含你的date的列是第二个(B):

 Dim i As Integer for i = 1 to cellsCount If Hour(Cells(i, 2)) < 7 Or Hour(Cells(i, 2) > 22 Then Rows(i).Delete Else If WeekDay(Cells(i, 2)) = 7 Or WeekDay(Cells(i, 2)) = 1 Then Rows(i).Delete End If next 

您可以在这里有关于WeekDayfunction的更多信息: http : //msdn.microsoft.com/en-us/library/82yfs2zh%28v=vs.90%29.aspx