[英]Excel Macro to replace string in multiple excel files
我正在嘗試創建一個 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
Excel 以需要明確的參考而聞名。 始終確保您的所有對象都具有以 root 身份指向應用程序 object 的路徑。
開始也是一個好習慣
option explicit
這有助於發現這些潛在的錯誤。
Tim 的代碼看起來不錯,應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.