宏基于数组抛出错误重新排列列

时间:2013-08-30 03:31:40

标签: excel excel-vba vba

我一直在寻找像这样的宏。

宏抛出1004错误,Columns(l + 1).Insert以黄色突出显示

This selection is not valid

Copy and past areas cannot overlap unless they'er the same size and shape

有107行,可能代码正在处理整个列而不仅仅是107行? 不知道如何修复这个

由于

Sub f()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
On Error GoTo Skipit
HeaderNames = Array("RespID", "Subject", "Tag", "Strengths Comments", "Improvement Comments")
For l = 0 To UBound(HeaderNames)
    Columns(Rows(1).Find(HeaderNames(l), , xlValues, xlWhole).Column).Cut
    Columns(l + 1).Insert
Skipit:
Next
ActiveSheet.UsedRange.Offset(, l).ClearContents
Application.ScreenUpdating = True
Application.DisplayAlerts = True
On Error GoTo 0
End Sub

1 个答案:

答案 0 :(得分:1)

您无法在同一个地方复制和粘贴。 这应该有效:

Sub f()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
On Error GoTo Skipit
Dim HeaderNames, l As Long, colFrom As Long

HeaderNames = Array("RespID", "Subject", "Tag", "Strengths Comments", "Improvement Comments")
For l = 0 To UBound(HeaderNames)
    colFrom = Rows(1).Find(HeaderNames(l), , xlValues, xlWhole).Column
    If l + 1 <> colFrom Then Columns(colFrom).Cut: Columns(l + 1).Insert
Skipit:
Next
ActiveSheet.UsedRange.Offset(, l).ClearContents
Application.ScreenUpdating = True
Application.DisplayAlerts = True
On Error GoTo 0
End Sub