工作中遇到的例子,做个记录。
在Excel中使用VBA方法:打开Excel,按住 ALT + F11,调出VBA窗口。
批量去除Excel 所有sheet表中筛选
Sub RemoveAllAutoFilter()
Dim sht As Worksheet
For Each sht In ActiveWorkbook.Worksheets
If sht.AutoFilterMode = True Then sht.AutoFilterMode = False
Next
End Sub
在A列添加sheet表的名字
每个sheet记录了每周不同产品的销量,要统计一年每周不同产品的总销量。在合并sheet前,要先把sheet表名写到每个sheet的第一列,便于之后统计。
Sub 在A列添加sheet的名字()
Dim sht As Worksheet
For Each sht In ThisWorkbook.Sheets
lr = sht.Cells(Rows.Count, "e").End(3).Row
With sht
.Range("A1").Value = "Week"
.Range("A2:A" & lr) = .Name
End With
Next sht
End Sub
合并Excel中的所有sheet
每个sheet的字段都是一致的。
1)先复制表头到新Excel,批量选中所有sheet,删除表头后,再合并sheet。
2)新建sheet,然后执行以下代码。
Sub 合并当前工作簿下的所有工作表()
Application.ScreenUpdating = False
For j = 1 To Sheets.Count
If Sheets(j).Name <> ActiveSheet.Name Then
X = Range("A65536").End(xlUp).Row + 1
Sheets(j).UsedRange.Copy Cells(X, 1)
End If
Next
Range("B1").Select
Application.ScreenUpdating = True
MsgBox "当前工作簿下的全部工作表已经合并完毕!", vbInformation, "提示"
End Sub
在A列添加sheet表的名字
合并不同Excel中的所有sheet。
1)把需要合并的Excel都放在一个文件夹里,并在这个文件夹里新建一个Excel。
2)打开Excel,再sheet标签上单击右键,选择“查看代码”。
3)在打开的VBA编辑窗口中粘贴以下代码:
Sub 合并当前目录下所有工作簿的全部工作表()
Dim MyPath, MyName, AWbName
Dim Wb As Workbook, WbN As String
Dim G As Long
Dim Num As Long
Dim BOX As String
Application.ScreenUpdating = False
MyPath = ActiveWorkbook.Path
MyName = Dir(MyPath & "\" & "*.xls")
AWbName = ActiveWorkbook.Name
Num = 0
Do While MyName <> ""
If MyName <> AWbName Then
Set Wb = Workbooks.Open(MyPath & "\" & MyName)
Num = Num + 1
With Workbooks(1).ActiveSheet
.Cells(.Range("B65536").End(xlUp).Row + 2, 1) = Left(MyName, Len(MyName) - 4)
For G = 1 To Sheets.Count
Wb.Sheets(G).UsedRange.Copy .Cells(.Range("B65536").End(xlUp).Row + 1, 1)
Next
WbN = WbN & Chr(13) & Wb.Name
Wb.Close False
End With
End If
MyName = Dir
Loop
Range("B1").Select
Application.ScreenUpdating = True
MsgBox "共合并了" & Num & "个工作薄下的全部工作表。如下:" & Chr(13) & WbN, vbInformation, "提示"
End Sub
Excel中每个sheet保存成单独的Excel
先将Excel放在一个文件夹。
Sub Splitbook()标签:常用,sht,Sub,Excel,End,Sheets,sheet From: https://blog.51cto.com/u_15483489/6040553
Dim xPath As String
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xWs.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub