按照指定工作表中的数据顺序对另一工作表中的数据排序
时间:2023-05-28 13:53:21
我从数据库中导入数据到工作表,本来数据库中的数据顺序是排好了的,然而导入工作表中后数据顺序变乱了。如果在工作表中使用复制粘贴来重新恢复固定的顺序,将会花费大量的时间,能否使用VBA快速完成排序,详情如下。
下图1中“固定顺序”工作表为数据本来应该的顺序:
图1
图2中“整理前”工作表为导入数据后的顺序:
图2
可以看出,“整理前”工作表中的列顺序被打乱了,我们需要根据“固定顺序”工作表中列的顺序将“整理前”工作表恢复排序。
实现上述目的的代码如下:
Sub OrderRange()
Dim wksYesOrder AsWorksheet
Dim wksNoOrder AsWorksheet
Dim wksNew As Worksheet
Dim lngLastFixed As Long
Dim lngLastVariable As Long
Dim lngNewCol As Long
Dim i As Long
Dim SearchHeader, rng
‘赋值工作表对象
Set wksYesOrder =Worksheets(“固定顺序”)
Set wksNoOrder =Worksheets(“整理前”)
Worksheets.Add Before:=wksNoOrder
ActiveSheet.Name = “整理后”
Set wksNew =Worksheets(“整理后”)
‘获取数据区域所在的最后一列
lngLastFixed =wksYesOrder.Range(“IV1”).End(xlToLeft).Column
lngLastVariable =wksNoOrder.Range(“IV1”).End(xlToLeft).Column
‘列计数变量
lngNewCol = 1
‘遍历”固定顺序”工作表列标题
For i = 1 To lngLastFixed
SearchHeader =wksYesOrder.Cells(1, i)
‘在”整理前”工作表中查找
With wksNoOrder
Set rng =.Range(.Cells(1, 1), .Cells(1, lngLastVariable)) _
.Find(SearchHeader, LookIn:=xlValues, LookAt:=xlWhole)
‘如果找到则将该列复制到”整理后”工作表
If (Not rng Is Nothing) Then
.Cells(1,rng.Column).EntireColumn.Copy _
wksNew.Cells(1, lngNewCol)
lngNewCol =lngNewCol + 1
End If
End With
Next i
End Sub
上述代码的图片版如下:
运行代码后的结果如下图3所示:
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
有了这6款Mac音乐插件 带你玩转音乐创作
![](https://img.aspxhome.com/file/2023/5/a210175_0s.jpeg)
Win10系统所有自带应用都打不开了怎么解决?
![](https://img.aspxhome.com/file/2023/26/a226353_0s.jpg)
Win10如何设置关机定时?Win10设置关机定时的方法
![](https://img.aspxhome.com/file/2023/25/a218748_0s.gif)
如何解决Win10开机黑屏只有鼠标?
![](https://img.aspxhome.com/file/2023/1/a278796_0s.png)
进程调度是什么意思?操作系统常见的五种进程调度算法
![](https://img.aspxhome.com/file/2023/6/a325514_0s.jpg)
Win7系统电脑USB接口无法使用解决方案
![](https://img.aspxhome.com/file/2023/27/a230387_0s.jpg)
win10如何关闭快速启动功能
![](https://img.aspxhome.com/file/2023/1/a280065_0s.png)
excel 隔列统计求和方法 SUM函数求和公式
![](https://img.aspxhome.com/file/2023/2/a162022_0s.gif)
Word中标题跟随正文样式缩进的解决办法
![](https://img.aspxhome.com/file/2023/3/34893_0s.png)
Adobe Experience Design CC 2019 for Mac(XD CC) 的提示和技巧
Win10系统鼠标右键菜单播放到设备的去除方法
![](https://img.aspxhome.com/file/2023/2/a285752_0s.jpg)
利用条件格式为excel单元格自动添加边框
word怎么去掉背景色?word背景色去掉方法
![](https://img.aspxhome.com/file/2023/3/24223_0s.jpg)
Win10右键菜单添加加密文件系统选项的方法
![](https://img.aspxhome.com/file/2023/26/a226389_0s.jpg)
HelioP60处理器怎么样_HelioP60评测、跑分、参数、相关手机及报价
![](https://img.aspxhome.com/file/2023/3/a296661_0s.jpg)
Win10笔记本连接不上WiFi怎么办 Win10笔记本连接不上WiFi图文解决教程
![](https://img.aspxhome.com/file/2023/28/a243424_0s.jpg)
Win11预览体验计划显示:你的电脑不满足Win11最低硬件需求怎么办?
![](https://img.aspxhome.com/file/2023/1/a281735_0s.png)
如何双面打印一个excel工作薄
Win10打开文件提示没有与之关联的程序的解决方法
![](https://img.aspxhome.com/file/2023/6/a325286_0s.jpg)
Word/Excel/PPT如何转换成PDF
![](https://img.aspxhome.com/file/2023/10/a345321_0s.gif)