需求提出:
test文件夹里面有3个excel文件,分别是1.xlsx,2.xlsx,3.xlsx,希望在不打开这三个excel文件的情况下,能够给每个文件的表格添加一列序号列,按行号进行排序。
请问用VBA怎么实现?
测试代码:
Sub test() Dim objFSO,objFolder,objFile As Object Dim strFolderPath As String Dim appTarget As Excel.Application Dim wbTarget As Workbook Dim wsTarget As Worksheet Dim lngLastRow As Long Dim strFileList As Variant Dim i As Integer strFolderPath = ThisWorkbook.Path & "\test\" strFileList = Array("1.xlsx", "2.xlsx", "3.xlsx") Set objFSO = CreateObject("Scripting.FileSystemObject") If Not objFSO.FolderExists(strFolderPath) Then MsgBox "找不到路径: " & strFolderPath, vbCritical, "错误" Exit Sub End If On Error GoTo ErrorHandler Set appTarget = New Excel.Application With appTarget .Visible = False .ScreenUpdating = False .DisplayAlerts = False End With For i = LBound(strFileList) To UBound(strFileList) Dim strPath As String strPath = strFolderPath & strFileList(i) If objFSO.FileExists(strPath) Then Set wbTarget = appTarget.Workbooks.Open(strPath) Set wsTarget = wbTarget.Worksheets(1) With wsTarget .Columns(1).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove .Range("A1").Value = "序号" lngLastRow = .Cells(.Rows.Count, 2).End(xlUp).Row If lngLastRow > 1 Then With .Range("A2:A" & lngLastRow) .Formula = "=ROW()-1" .Value = .Value End With End If .Columns(1).AutoFit End With wbTarget.Close SaveChanges:=True End If Next iCleanExit: If Not appTarget Is Nothing Then appTarget.Quit Set appTarget = Nothing End If Set objFSO = Nothing MsgBox "任务处理完成!", vbInformation, "提示" Exit SubErrorHandler: MsgBox "运行过程中发生错误: " & Err.Description, vbCritical Resume CleanExitEnd Sub
经测试通过,速度还可以。
主要是最近我的桌面上很多excel文件,搞得我很烦躁。来来回回地在多个Excel表格中机型切换,人都是懵的。
所以有的excel文件确实需要添加一列序号列,这样一来就相当于一个定位。虽然单元格定也可以定位,但毕竟还是太慢。
今天的分享就到这儿啦,非常感谢您对“Python SQL审天下”公众号的关注和点赞。如果您觉得我的公众号能给您带来一丝丝的收获,请多多转发给您的朋友圈,让更多的人看到并了解。也许您不经意间的点赞和转发,会给他人带来独特的体验和感受。