Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Excel 2007 VBA code to run search/replace on multiple worksheets ?

Status
Not open for further replies.

TomYC

Technical User
Dec 11, 2008
191
US
I have a file with numerous worksheets. Every time I add new, imported data to the file, I must run a search and replace on one or more columns in one or more worksheets, or else my data is not "cleaned." I would like to automate this in case I forget!
Surely there is an OnClose event in which all cells in worksheets could be selected, and a search and replace operation run that strips off some unnecessary text strings, after which the file is saved, or even as part of the save process.
I have experimented with macros, would prefer code idea...
Thanks--
T.Y.


 


then you don't need the sheet array.

Record your macro again without selecting those sheets.

Skip,

[glasses]Just traded in my old subtlety...
for a NUANCE![tongue]
 
The thing is, I'd like to have this code run on either all sheets, or all of the ones I had indicated, regardless of which is the active sheet at the point of saving the file.
This current code:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
NSUH
End Sub
Sub NSUH()

Cells.Select
Selection.Replace What:="NSUH - ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
ThisWorkbook.Save

End Sub

works if the only sheet of interest is the active sheet. But if I wanted to be certain, I'd have to select each sheet and then save.
Is there a problem with the Sheets(Array.Activate coding that I took out?
 


Then Select them in a ListBox.

Run the Find/Replace in a loop on each sheet.

Skip,

[glasses]Just traded in my old subtlety...
for a NUANCE![tongue]
 
How about this?
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
NSUH
End Sub
This way, anytime any active sheet is deactivated, the macro code runs (I took out the save portion!).
 
Except...that when I tried to select all many sheets at once, I got an automation error...when I then clicked/actived one of the many sheets selected. A run time error that suggested I had stressed out Excel and the 'object' got 'disconnected.'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top