|
Sub OpenAllExcelWorkbooks()
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim fldr As FileDialog
Dim myFolder As String
Dim ws As Worksheet
Dim searchString As String
Dim replaceString As String
Dim searchString1 As String
Dim replaceString1 As String
Application.DisplayAlerts = False
Application.ScreenUpdating = False
searchString = "xxx" '需要查找的字符
replaceString = "zzz" '用于替换的字符
' 设置初始文件夹路径变量
myPath = "E:\xxxx\xxxx\xxxx\" ' 修改为你的路径
' 创建FileDialog对象以便选择不同的文件夹
Set fldr = Application.FileDialog(msoFileDialogFolderPicker) '需要选到最后一级
' 显示文件夹选择对话框
If fldr.Show = -1 Then
myFolder = fldr.SelectedItems(1) & "\" ' 获取选择的文件夹路径
End If
' 确保路径以反斜杠结束
If Right(myFolder, 1) <> "\" Then myFolder = myFolder & "\"
' 设置Excel文件的扩展名
myExtension = "*.xls*"
' 获取文件夹内第一个Excel文件
myFile = Dir(myFolder & myExtension)
' 如果找到文件则进行循环
Do While myFile <> ""
' 打开Excel文件
Workbooks.Open Filename:=myFolder & myFile
'遍历所有工作表
For Each ws In ActiveWorkbook.Worksheets
'在工作表的范围A1:Z100内查找并替换字符
ws.Range("A1:Z100").replace What:=searchString, Replacement:=replaceString, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
Next ws
searchString1 = "aaa" '需要查找的字符
replaceString1 = "bbb" '用于替换的字符
'遍历所有工作表
For Each ws In ActiveWorkbook.Worksheets
'在工作表的范围A1:Z100内查找并替换字符
ws.Range("A1:Z100").replace What:=searchString1, Replacement:=replaceString1, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
Next ws
MsgBox "替换完成!"
ActiveWorkbook.Save
ActiveWorkbook.Close
' 获取下一个文件名
myFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
麻烦各位大神帮我看看,这段代码为什么运行之后excel都回自动闪退?顺便帮我优化一下代码,本人小菜鸟一枚,万分感谢!!
|
|