使用名称作为date在Excel中使用VBA对工作表进行sorting
我正在为我的Excel电子表格写一个自定义的sorting程序,至less有3个工作表。 在第一个位置,我把名为“摘要”的工作表,第二个是“数据”,其余的是名称为“17.03.2011”,“20.03.2011”等date的工作表等需要按时间顺序sorting。
这是我到目前为止,脚本停止与DateDiff()符合“Object Required”错误,我不知道为什么:纠正下面的代码后,我仍然有麻烦,使事情sorting在右边订购。 任何人都可以提出一种方法来比较和移动床单?
Public Sub ssort() sSummary.Move before:=Worksheets.Item(1) sData.Move after:=sSummary Dim i, n As Integer Dim diff As Long Dim current, other As Worksheet For i = 1 To Worksheets.Count Set current = Worksheets.Item(i) If current.Name <> sData.Name And current.Name <> sSummary.Name Then For n = i + 1 To Worksheets.Count Set other = Worksheets.Item(n) diff = DateDiff(DateInterval.day, Format(current.Name, "dd.mm.yyyy"), Format(other.Name, "dd.mm.yyyy")) If diff > 0 Then current.Move before:=other Debug.Print "Moving " & current.Name & " before " & other.Name ElseIf diff < 0 Then current.Move after:=other Debug.Print "Moving " & current.Name & " after " & other.Name End If Next n End If Next i End Sub
我想我要么不明白DateDiff()或格式(),任何人都可以请说明这一点?
在从http://www.vbaexpress.com/kb/getarticle.php?kb_id=72上的在线示例中修改代码以使用datediff进行比较之后,我想出了一个按预期工作的解决scheme:
Sub sort2() sSummary.Move before:=Worksheets.Item(1) sData.Move after:=sSummary Dim n As Integer Dim M As Integer Dim dsEnd, lowest As Integer Dim dCurrent() As String Dim dOther() As String Dim diff As Long dsStart = 3 dsEnd = Worksheets.Count For M = dsStart To dsEnd For n = M To dsEnd If Worksheets(n).Name <> "Summary" And Worksheets(n).Name <> "Data" And Worksheets(M).Name <> "Summary" And Worksheets(M).Name <> "Data" Then dCurrent = Split(CStr(Worksheets(n).Name), ".") dOther = Split(CStr(Worksheets(M).Name), ".") diff = DateDiff("d", DateSerial(dCurrent(2), dCurrent(1), dCurrent(0)), DateSerial(dOther(2), dOther(1), dOther(0))) If diff > 0 Then Worksheets(n).Move before:=Worksheets(M) End If End If Next n Next M End Sub
DateDiff
函数要求两个date参数是Variant (Date)
types。 相反,你给它两个String
参数,这是Format
函数返回。
您需要将每个string转换为Variant (Date)
。 这可以这样做:
strDate = current.Name ' String: "20.03.2011" aintDateElements = Split(strDate, ".") ' Array: {2001, 03, 20} varDate = DateSerial(aintDateElements(2), aintDateElements(1), aintDateElements(0)) ' Variant (Date)
还有其他方法可以进行这种转换,但是我发现这是最less出现意想不到的结果的方式!
如果您将此代码从Web上移除,请注意DateInterval不是本机Excel对象或VBA对象,而是.Net对象。 你可以用“d”代替“DateInterval.day”。
diff = DateDiff("d", Format(current.Name, "dd.mm.yyyy"), _ Format(other.Name, "dd.mm.yyyy"))
如果您在Format / Datediff调用中收到错误消息,请尝试将它们拆分为单独的语句。 你会看到问题在哪里。
例:
dtStart = CDate(Format(current.Name, "dd.mm.yyyy")) dtEnd = CDate(Format(other.Name, "dd.mm.yyyy")) diff = DateDiff("d", dtStart, dtEnd)