错误1004 – 此select在Range.Insert上无效

我得到一个运行时错误1004 – 这个select不是有效的错误,当试图在excel中运行一个VBA AMCRO。

我已经四处寻找解决scheme,所有我已经尝试过的都不成功(激活工作表,清除数据下面的行以确保有插入空间,其他我不记得)。

我在做什么:

我们有一个数据集,需要根据三列进行sorting,不幸的是,内置的sorting不能按我们的意愿工作。 三列是机器,class次和date/时间。 示例数据(按日​​期/时间sorting):

Machine1 Days 02/05/2013 07:05 Machine2 Days 02/05/2013 07:05 Machine1 Days 02/05/2013 08:45 Machine1 Late 02/05/2013 15:05 

我们希望对此进行sorting,使其看起来像这样:

 Machine1 Days 02/05/2013 07:05 Machine1 Days 02/05/2013 08:45 Machine2 Days 02/05/2013 07:05 Machine1 Late 02/05/2013 15:05 

我的代码:

 For rowCount = 4 To 5000 On Error GoTo nextLoop Worksheets("Schedule").Activate If ActiveSheet.Cells(rowCount, 1).Value = "" Then Exit For End If If ActiveSheet.Cells(rowCount + 1, 1).Value = "" Then Exit For End If thisMachine = ActiveSheet.Cells(rowCount, 2).Value thisShift = ActiveSheet.Cells(rowCount, 4).Value thisDay = Mid(ActiveSheet.Cells(rowCount, 5).Value, 1, 10) pasteRow = rowCount + 1 If ActiveSheet.Cells(rowCount + 2, 4).Value <> thisShift Then GoTo nextLoop End If For internalCount = rowCount + 1 To 5000 If ActiveSheet.Cells(internalCount, 4).Value <> thisShift Then Exit For End If If Mid(ActiveSheet.Cells(internalCount, 5).Value, 1, 10) <> thisDay Then Exit For End If If ActiveSheet.Cells(internalCount, 2).Value = thisMachine Then Range(internalCount & ":" & internalCount).Cut Range(pasteRow & ":" & pasteRow).Insert pasteRow = pasteRow + 1 End If Next internalCount nextLoop: Next rowCount 

这适用于其中一个文件,但另一个格式相同的文件产生错误,并且debugging突出显示了行Range(pasteRow & ":" & pasteRow).Insert为问题。

数据首先按date/时间sorting(未显示),这也使得class次顺序。 然后循环遍历表的每一行,每行检查下面的每一行。 如果下面的行包含同一天,并且使用相同的机器,那么该行将被剪切并粘贴到正在读取的当前行或粘贴的前一行( pasteRow )下。 这会尽量保持机器的时间顺序。 如果date或class次不匹配,则“内部”循环转义并且程序移动到下一行。

任何人都可以看到为什么这会造成一个问题? 或者为什么它可以用于一组数据而不是第二组?

对不起,如果不清楚,我已经尽力解释,但很难用文字来形容。

谢谢,

克里斯

我想你需要按日 〜> Shift〜 > Machine〜 > Time来sorting。

如果是这样的话,那么您需要一个类似的vba代码来解决Excel 2003的限制,请参阅MrExcel获取更多详细信息:

 Range("A1:J1000").Sort Key1:=Range("B2"), Order1:=xlAscending, _ Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:= _ xlTopToBottom, DataOption1:=xlSortNormal Range("A1:J1000").Sort Key1:=Range("F2"), Order1:=xlAscending, Key2:=Range _ ("G2"), Order2:=xlAscending, Key3:=Range("A2"), Order3:=xlAscending, _ Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:= _ xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal, _ DataOption3:=xlSortNormal