代码运行,但是找不到/替换值。
我认为问题在于工作表和替换方法的for循环中
Sub UGA()
'PURPOSE: Loop through all Excel files in a user specified folder and perform a set task on them
Dim wb As Workbook
Dim ws As Worksheet
Dim myPath, myFile, myExtension As String
Dim fnd, rep As Variant
Dim FldrPicker As FileDialog
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'find and replace with blank
fnd = "find this"
rep = ""
'Loop through each worksheet in ActiveWorkbook
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.Replace What:=fnd, Replacement:=rep, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next ws
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Complete!"
End Sub
期望找到定义的值并替换为空格(“”)
答案 0 :(得分:1)
您的代码依赖于Active Workbook
,这可能是罪魁祸首。
将For Each ws In ActiveWorkbook.Worksheets
更改为For Each ws in wb.Worksheets
以明确引用该工作簿。
您还使字符串fnd
和rep
变暗了。这些应该是字符串,并且简写声明两个变量的正确方法是Dim fnd as String, rep as String
。实际上,您将两个变量都声明为变量。
答案 1 :(得分:1)
Sub UGA()
'PURPOSE: Loop through all Excel files in a user specified folder and perform a set task on them
Const fnd As String = "find this"
Const rep As String = ""
Const cStrExtensions As String = "*.xls*"
Dim ws As Worksheet
Dim strFolderPath As String ' Search Folder
Dim strFileName As String ' Current File Name (Workbook)
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
On Error GoTo ProcedureExit
' Choose Search Folder
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = False Then Exit Sub
strFolderPath = .SelectedItems(1) & "\"
End With
' Loop through folder to determine Current File Name (Workbook).
strFileName = Dir(strFolderPath & cStrExtensions)
' Loop through files in folder.
Do While strFileName <> ""
' Open each file in folder
Workbooks.Open strFolderPath & strFileName
With ActiveWorkbook
' Loop through each worksheet in ActiveWorkbook
For Each ws In .Worksheets
ws.Cells.Replace What:=fnd, Replacement:=rep, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next
.Close True
End With
strFileName = Dir()
' Exclude this workbook.
'If ThisWorkbook.Name = strFileName Then strFileName = Dir()
Loop
'Message Box when tasks are completed
MsgBox "Complete!"
ProcedureExit:
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub