首页 > 解决方案 > Excel VBA:更改原始数据表的列顺序会影响工作簿中的所有其他表

问题描述

我一直在处理一个工作簿,我在其中导入原始数据表,并且工作簿中到处都有对这些工作表中列的引用。我遇到的一个问题是,有时列不在正确的位置,因此我一直在使用脚本对列重新排序,主要是为了可以在整个工作簿中使用 VLOOKUPS 而不是 INDEX/MATCH。这是我用来重新排序列的代码,我在这里某处找到的:

Sub reOrder_Metadata_Columns()

'Running this script will put the columns in the Metadata table in the order specified
'This is important because now we can use VLOOKUP to get the proper column


Dim arrColOrder As Variant, Ndx As Integer
Dim found As range, counter As Integer

'This is the correct order of the columns:
arrColOrder = Array("Field1", " Field2", "Field3", "Field4", "Field5”)


counter = 1

Application.ScreenUpdating = False

For Ndx = LBound(arrColOrder) To UBound(arrColOrder)

    Set found = Sheets("Metadata").Rows("1:1").Find(arrColOrder(Ndx), LookIn:=xlValues, lookat:=xlWhole, _
                      SearchOrder:=xlByColumns, searchdirection:=xlNext, MatchCase:=False)

    If Not found Is Nothing Then
        If found.Column <> counter Then
            found.EntireColumn.Cut
            Sheets(“Metadata").Columns(counter).Insert Shift:=xlToRight
            Application.CutCopyMode = False
        End If
        counter = counter + 1
    End If

Next Ndx

Application.ScreenUpdating = True

End Sub

直到今天它工作正常,由于某种原因,同一工作簿中其他工作表中的所有引用都在列中查找,例如 Field1 曾经是,现在可能是第 2 列。我如何保留其余部分当我更改原始数据文件中列的顺序时,工作簿的内容会发生变化吗?我尝试使用绝对引用,例如,在不同的页面上:

 =Metadata!$A1 

并将其全部复制到列中,但是当我重新排序元数据表时它仍然会发生变化。

标签: excelvba

解决方案


推荐阅读