Run an Excel VBA script on only the active worksheet and not the entire book? - vba

I am using a VBA script to essentially find/replace. Right now when I run the VBA script it applies to all open sheets in the workbook. I wish for the VBA script to only apply in the active sheet and not touch the rest.
Here is my current macro code:
Sub ReplaceCC()
'
' ReplaceCC Macro
' Add CC to Distributor, Reseller, Government and Retail.
'
'
Range("A1").Select
Cells.Replace What:="Distributor", Replacement:="DistributorCC", LookAt:= _
xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Cells.Replace What:="Reseller", Replacement:="ResellerCC", LookAt:=xlPart _
, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Cells.Replace What:="Government", Replacement:="GovernmentCC", LookAt:= _
xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Cells.Replace What:="Retail", Replacement:="RetailCC", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
Here is the entire VBA script with all subs.

I got the same problem. It depends of the Find/Replace history: if in the previous manual use of Find/Replace, you specified "Options > Search in Workbook", your macro will apply to all sheets. Otherwise, with the default "In Sheet", the macro will stay in the original Worksheet. I still don't know how to fix that from within the macro, though.

Interesting question. I believe that you could do what you're trying to do by simply placing "ActiveSheet" before each object reference in your code.
For example: Instead of Range("A1").Select use ActiveSheet.Range("A1").select
If you set up your code like this, whenever you execute, it should carry out its actions on the worksheet you currently have active.
EDIT: You should check to see which module you have this code placed in. If it is in an inserted module, I think you should be fine. On the other hand, if you've inserted it in one of the sheet modules it will only modify the sheet it is attached to. If you insert ActiveSheet before your cell references and the rest it will still modify the active sheet instead of the sheet the code is attached to.

It seems the macro was not recognizing the active sheet properly since the sheets were copies of each other. If you copy the content on Sheet 1 and create a new sheet then paste the content on it this will work. Each sheet needed to be unique and not just a copy of the original.

This is due to a VBA bug. When you use "Find" in VBA, the parameter "LookAt:=xlPart" or "LookAt:=xlWhole" works as expected. But when you use "Replace", the coded parameter is ignored and the replace uses the last MANUAL setting for its scope. The workaround is to do a "Find" operation right before the "Replace" operation, since "Find" uses the coded "LookAt" scope (thereby making the "Find"'s scope the last setting used, so the "Replace" will then use the scope coded into the "Find").

Solution from http://www.vbaexpress.com/forum/showthread.php?11444-Solved-Replace-in-a-sheet-and-not-the-entire-workbook
Dim dummy As Range
Set dummy = Worksheets(1).Range("A1:A1").Find("Dummy", LookIn:=xlValues)
Then you can post REPLACE functions underneath these lines of codes

Related

Return cell row and column of a cell after using find

I am searching for a VBA command that in combination with find() (or similar) returns the address of the found cell in a fixed column.
Due to the programm, the value I am searching for exists only once, but apparently I could only return its value, not its location.
Set Cell = Selection.Find(What:=Choice, LookIn:=xlFormulas,_
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext,_
MatchCase:=False, SearchFormat:=False)
It is probably an easy question, but help is much appreciated!
Write after your code:
debug.print cell.row
debug.print cell.column

Creating VBA code to reference cell text and create a dynamic Find & Replace

I work with multiple excel spreadsheets that require monthly updates for month end financial closing. I need to change references to outside workbooks so that it pulls in data from the current months file.
For example changing
"C:\Desktop\Folder\June"
to
"C:\Desktop\Folder\July"
I want to be able to enter the two months into specific cells in the worksheet and then run a VBA script to auto update the references throughout the workbook. I can record a "macro" for the Find & Replace function, but I can't figure out how to point the "Find" and "Replace" variables to the specific cells where I store the month values.
Here is the current code I have for conducting find and replace:
ActiveCell.Replace What:="Jun", Replacement:="Jul", LookAt:=xlPart, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Replace the literal text strings of "Jun" and "Jul" with a cell reference. For this, you can use Range("A1"). Of course, you would put in the actual range.
ActiveCell.Replace What:=Range("A1"), Replacement:=Range("B1"),LookAt:=xlPart, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False`
What you should do is give those cells names then you can reference the cells
Range("find1").Select
ActiveCell.FormulaR1C1 = "July"
Range("find2").Select
ActiveCell.FormulaR1C1 = "July"

VBA Run-time error 9 With Sheet

So here I have VBA code that is a part of my function, yet whenever I run it, I get the following error:
Run-Time error '9': Subscript out of range
The actual worksheet exists. In the vba editor on the side panel, it appears as Sheet2(Data_Sheet). In the details in that panel, it shows (Name) as being Sheet 11 and Name as being Data_Sheet. Dos anybody know a possible source of this error? My code is below:
With Sheets("Data_Sheet")
'this searches just row 1
Set header_cell_1 = .Rows(1).Find(What:="One", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
Set header_cell_2 = .Rows(1).Find(What:="Two", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
Set header_cell_3 = .Rows(1).Find(What:="Three", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
Set header_cell_4 = .Rows(1).Find(What:="Four", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
Set header_cell_5 = .Rows(1).Find(What:="Five", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
Set header_cell_6 = .Rows(1).Find(What:="Six", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
Set header_cell_7 = .Rows(1).Find(What:="Seven", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
col_1 = header_cell_1.Column
col_2 = header_cell_2.Column
col_3 = header_cell_3.Column
col_4 = header_cell_4.Column
col_5 = header_cell_5.Column
col_6 = header_cell_6.Column
col_7 = header_cell_7.Column
End With
As from comments, the macro is running from the PERSONAL.XSLB workbook so it's trying to finding the Sheets("Data_sheet") in it, and clearly not finding because it is into another workbook --> Subscript out of range.
To fix, always use full references of the Object you work with:
With Workbooks("myWorkbook.xlsm").Sheets("Data_sheet") '<-- explicitly saying in which workbook it must look for the sheet
End With
Alternatively, remember that:
ThisWorkbook references the workbook the code runs from. In your case, it would reference the PERSONAL.XLSB;
ActiveWorkbook references the currently active workbook. Very risky to use (usually, you should know which workbook you want to target). But there might be some cases in which you want the code to intentionally running on the active workbook (see the example of an add-in: the code runs from the add-in, but you want the add-in to run on the workbook from which is used).
WARNING:
A common error is not to use any reference, like in your case:
With Sheets("Data_Sheet") '<-- of which workbook?
In that case, VBA answers the question itself with ActiveWorkbook, which is the default object. Only if you explicitely want to run from the ActiveWorkbook you should leave it like that; otherwise, always reference the object to avoid any bug related to this.

Excel VBA - Paste into Find Command

I'm trying to create a macro which searches for a string of text that has been entered/selected from another cell. When I record the macro, it sets the "What" part of the find function as the specific text that was copied when recording the macro, rather than a Paste Selection, which is what I want.
Sub GOTOSECTION() ' ' GOTOSECTION Macro '
'
Range("B7").Select
Selection.Copy
Cells.Find(What:="Section 4A", After:= _
ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Cells.FindNext(After:=ActiveCell).Activate
End Sub
But I want the "What:" to be the value copied from cell B7. When I try to input a paste command in there it gives me a syntax error, so I'm sure it's something really basic I'm missing (I'm pretty green when it comes to vba, and I've been unable to find examples of what I'm looking for online).
Thanks for any input!
Replace What:="Section 4A" with What:=ActiveCell.Value
This will get the current value of the currently selected cell (though it might (though I'm not 100% sure without checking) cause some errors if the cell is blank, so consider error checking).
EDIT:
If you're continuing to use the macro recording in the future, it might be worth looking into relative references. I've never used it for anything like this, so I'm not sure if it will have an effect, but it could, so check it out.

Sort a Column in Another Sheet Without Selecting That Sheet

Is it possible to sort columns in another sheet without selecting that sheet?
The problem is while I am running this code, I want this sheet to be hidden and I do not want it to flash over to it when I need to sort the table. Here is my code... This works, but it does obviously select the sheet and shows you the other sheet. Maybe something with 'make active sheet' would work can you do that then say 'make active cell'. I am not sure. Thanks guys.
Application.Worksheets("RawDataLines").Select
Application.Worksheets("RawDataLines").Range("Q5").Select
Application.Worksheets("RawDataLines").Range("A4:R1007").Sort Key1:=Range("Q5"), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Application.Worksheets("RawDataLines").Range("A5").Select
Application.Worksheets("RawDataLines").Range("A4:R1007").Sort Key1:=Range("A5"), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
This:
Application.Worksheets("RawDataLines").Select
Application.Worksheets("RawDataLines").Range("Q5").Select
Application.Worksheets("RawDataLines").Range("A4:R1007").Sort ...
Could be this:
With Application.Worksheets("RawDataLines")
.Range("A4:R1007").Sort Key1:= .Range("A5")'...
End With
Add ScreenUpdating
Application.ScreenUpdating = False
#Your Code
Application.ScreenUpdating = True
Just make sure that you set the select back to the sheet you want it on prior to setting ScreenUpdating = True
Here the problem comes with the Key1 arguments of VBA sort method. Even though we explicitly pass range with relevant sheet, when it comes to Key1:=Range(…), VBA automatically take ActiveSheet.Range(…).
If We have selected some other sheet instead of the sheets of sort data, VBA shows runtime error.
To fix this problem change the code as Key1:=Your_Sheet_With_Data.Range(Your_Range). For Example, above referred code can be fixed changing the code as
Key1:=Worksheets("RawDataLines").Range("Q5")