我对VBA非常陌生,所以请忍受这个问题。 首先,我复制了位于桌面上某处的5个工作簿的最后两个工作表。 如果工作表名称以" ma_SMS"开头,我想对数据进行排序。基于该工作表的第一列。
我尝试了以下代码:
Sub MergeExcelFiles()
Dim fnameList, fnameCurFile As Variant
Dim countFiles, countSheets As Integer
Dim wksCurSheet As Worksheet
Dim wbkCurBook, wbkSrcBook As Workbook
Dim strDataRange As Range
'Delcaring the keyRange as range store the Sort key range to sort by
Dim keyRange As Range
'Assigning the target sort Range to strDataRange
fnameList = Application.GetOpenFilename(FileFilter:="Microsoft Excel Workbooks (*.xls;*.xlsx;*.xlsm;*.csv),*.xls;*.xlsx;*.xlsm;*.csv", Title:="Choose Excel files to merge", MultiSelect:=True)
Path = "C:\Users\se\Desktop"
outputName = "output.xlsx"
If (vbBoolean <> VarType(fnameList)) Then
If (UBound(fnameList) > 0) Then
countFiles = 0
countSheets = 0
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set wbkCurBook = ActiveWorkbook
For Each fnameCurFile In fnameList
Set wbkSrcBook = Workbooks.Open(Filename:=fnameCurFile)
countFiles = countFiles + 1
countSheets = wbkSrcBook.Sheets.Count 'total sheets in this workbook
For Each wksCurSheet In wbkSrcBook.Sheets
'last sheet got an index equal to countSheets.
'the sheet before the last one will be then countSheets-1
If wksCurSheet.Index = countSheets Or wksCurSheet.Index = (countSheets - 1) Then wksCurSheet.Copy after:=wbkCurBook.Sheets(wbkCurBook.Sheets.Count)
Next
For Each wksCurSheet In wbkSrcBook.Sheets
If wksCurSheet.Name = "ma_SMS%" Then 'Delcaring the strDataRange as range store the target range to sort
Dim strDataRange As Range
'Delcaring the keyRange as range store the Sort key range to sort by
Dim keyRange As Range
'Assigning the target sort Range to strDataRange
Set strDataRange = Range("A1:S400")
Set keyRange = Range("A1")
'Sorting the data using range objects and Sort method
strDataRange.Sort Key1:=keyRange, Header:=xlYes
Next
End If
wbkSrcBook.Close SaveChanges:=False
Next
fName = Application.GetSaveAsFilename
wbkCurBook.SaveAs Filename:=fName
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Procesed " & countFiles & " files" & vbCrLf & "Merged 2 worksheets from each workbook", Title:="Merge Excel files"
End If
Else
MsgBox "No files selected", Title:="Merge Excel files"
End If
End Sub
但它没有对数据进行排序。请帮忙