excel - Excel宏替换多个excel文件中的字符串
问题描述
我正在尝试创建一个 VB 宏来替换在目录中的多个 excel 文件中找到的字符串。我的代码在下面,但它不起作用,我不确定我需要做什么来修复它。
有什么建议么 ?
Sub ReplaceStringInExcelFiles()
Dim MyFile As String
Dim FilePath As String
Dim orig As String
Dim news As String
orig = "cow"
news = "dog"
FilePath = "C:\myDir\"
MyFile = Dir(FilePath)
Do While Len(MyFile) > 0
Workbooks.Open (FilePath & MyFile)
For q = 1 To Application.Worksheets.Count
Worksheets(q).Activate
Sheets("Sheet1").Cells.Replace what:=Original_String, Replacement:=New_Replacement_String, lookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next q
ActiveWorkbook.Save
ActiveWorkbook.Close
MyFile = Dir
Loop
End Sub
解决方案
尝试这个:
Sub ReplaceStringInExcelFiles()
Dim MyFile As String
Dim FilePath As String
Dim orig As String
Dim news As String
Dim wb As Workbook, ws As Worksheet
orig = "cow"
news = "dog"
FilePath = "C:\myDir\"
MyFile = Dir(FilePath & "*.xls*")
Do While Len(MyFile) > 0
Set wb = Workbooks.Open(FilePath & MyFile) '<< assign the workbook to wb
'Loop over the worksheets
'Note: no need to activate/select
For Each ws In wb.Worksheets
ws.UsedRange.Cells.Replace what:=orig, _
Replacement:=news, _
lookAt:=xlPart, SearchOrder:=xlByRows, _
MatchCase:=False
Next ws
ActiveWorkbook.Close savechanges:=True
MyFile = Dir
Loop
End Sub
推荐阅读
- html - HTML 输入和按钮未按比例调整大小
- c# - 如何以编程方式修改 VisualBrush?
- python - 在 Python 中使用组屏蔽约束将列表分成随机块/组合
- git - git,签出到 master 上的特定提交
- html - 如何自动加载 Lightbox 2?
- sql-server - 父子表和派生外键的最佳数据库设计 On delete Cascade
- html - 将网页中的字体颜色刮到excel中
- javascript - 自动重叠 SVG 边缘
- python - 结合两个熊猫系列列表:1)一个包含历史时间序列,2)另一个包含预测时间序列
- salesforce - 流程自动化 SuperBadge 第 5 步 - 如何正确验证机会何时是协商/审查