当我 运行 宏时,出现此错误。 Run-time错误9:下标超出范围错误

When i run the Macro, i am getting this error. Run-time error 9: Subscript out of range error

我正在寻找一个宏,用于根据 header 列重新排列列。我在这个平台上找到了下面的宏。当我尝试 运行 这个宏时,它工作正常但最后我在这行代码处收到错误。

If cel.value=correctOrder(col - 1) Then

这是错误

"Run-time error '9': Subscript out of range

下面是宏

Sub rearrange_Cols()
Dim correctOrder() As Variant
Dim lastCol As Long
Dim headerRng As Range, cel As Range
Dim mainWS As Worksheet

Set mainWS = ActiveWorkbook.Worksheets("Base")

' Edit this to be the correct order you need
correctOrder() = Array("FT Id", "FT Name", "FT Primary Location", "Deployed Location", " Approval Status", "Approved By", " Approved on Date", "FT acceptance Status", "Skill", " Billed", "Date of Joining"," Year" )
' Now, we know that the number of headers you have to rearrange are `UBound(CorrectOrder)+1`


With mainWS
    lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    Set headerRng = .Range(.Cells(1, 1), .Cells(1, lastCol))
End With

Dim newWS As Worksheet
Set newWS = ActiveWorkbook.Sheets.Add
newWS.Name = "New Open"

Dim col As Long
With newWS
    For col = 1 To lastCol
        For Each cel In headerRng
            If cel.Value = correctOrder(col - 1) Then
                mainWS.Columns(cel.Column).Copy .Columns(col)
                Exit For
            End If
        Next cel
    Next col
End With

当您的 Base 工作表超过 12 列时出现问题。

例如,如果工作表有 13 列。
lastCol 变量设置为 13。
它被传递到 col 变量中,当它达到 13 并在 correctOrder(col - 1) 中使用时,会生成 下标超出范围 错误。
correctOrder 数组有 12 个元素(从零开始),因此当它试图找到第 13 个时,它超出了范围。

简单的解决方法是对 lastCol 值进行硬编码。

With mainWS
    lastCol = 12
    Set headerRng = .Range(.Cells(1, 1), .Cells(1, lastCol))
End With