Related
I am going to try to explain this as effectively as possible, so please bear with me.
I have various sheets called "Blasted" followed by a number 1 to x.
I want to loop through Column A of each sheet "Blasted" and find various strings within the columns. Once the value has been found, it must be copied to a sheet called "Blast List".
In the Sheet "Blast List", I have a cells in Column A with the same names as the sheets (Blasted 1 and so on) going down the column.
I have done the following code and managed to get Blasted 1 working, but want to make it more elegant and need help getting it to do all sheets called "Blasted"
Sub CopyBlastSheetData()
Dim e As String
Dim g As String
Dim h As String
Dim i As String
Dim j As String
Dim k As String
Dim l As String
Dim m As String
Dim n As String
Dim o As String
Dim p As String
Dim q As String
Dim r As String
Dim s As Long
Dim CStep As Long
Dim xCount As Integer
Dim ws As Worksheet
Dim ws1 As Worksheet
e = "PU"
g = "LINE TEST"
h = "EXTRA DETS"
i = "INTERMITTENT CONNECTION DETS"
j = "MISSING DETS"
k = "OUT OF ORDER DETS"
l = "INCOHERENT DETS"
m = "DELAY ERRORS DETS"
n = "CHARGE"
o = "ADDITIONAL MISSING DETS"
p = "LOW ENERGY DETS"
q = "ADDITIONAL INCOHERENT DETS"
r = "FIRE"
CStep = 1
For s = 1 To ActiveWorkbook.Sheets.Count
If InStr(1, Sheets(s).Name, "Blasted") > 0 Then xCount = xCount + 1
Next
While CStep < xCount
Do
Set ws = ThisWorkbook.Worksheets(CStr("Blasted " & CStep))
Set ws1 = ThisWorkbook.Worksheets("Blast List")
ws.Select
Range("A1").Select
Cells.Find(What:=e, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("E3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=g, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("G3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=h, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("H3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=i, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("I3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=j, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("J3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=k, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("K3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=l, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("L3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=m, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("M3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=n, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("N3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=o, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("O3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=p, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("P3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=q, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("Q3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ws.Select
Range("A1").Select
Cells.Find(What:=r, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
ws1.Select
Range("R3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Wend
CStep = CStep + 1
Next
End Sub
The idea is to ultimately look at the name of the sheet in Blast List in Column A, Select the Sheet with the same name as the text in the cell ("Blasted 1"), find the strings (e to r in the code), copy the cell, paste the cell to the next open cell in the same row as the name of the sheet in the sheet called Blast List.
Once completed, loop to the next sheet (e.g "Blasted 2") and copy and paste again.
This must be done until there is no more sheets called Blasted
Also if the string being searched for is not found, it must put "No Event" in the correct cell in Blast List.
Please help
Hi I managed to find a way to do it using the entire weekend playing:
Heres the code I used:
Sub CopySingle()
Dim wsfr As Worksheet
Dim wsl As Worksheet
Dim BlNumber As String
Dim BSStep As Long
Dim SI As String
Dim Srng As Range
Dim Nrng As Range
Dim Rrng As Range
Dim Brng As Range
Dim Arng As Range
Application.ScreenUpdating = False
BSStep = 1
Set Rrng = ThisWorkbook.Worksheets("Blast List").Range("A3", Range("A3").End(xlDown))
Set Srng = ThisWorkbook.Worksheets("Blast List").Range("E1:Q1")
For Each Brng In Rrng.Cells
For Each Nrng In Srng.Cells
On Error Resume Next
SI = Nrng.Value
BlNumber = CStr("Blasted " & BSStep)
Set wsfr = ThisWorkbook.Worksheets(CStr(BlNumber))
Set wsl = ThisWorkbook.Worksheets("Blast List")
wsfr.Select
Range("A1").Select
Cells.Find(What:=SI, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
Sheets("Blast List").Select
Range("A1").Select
Cells.Find(What:=BlNumber, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).End(xlToRight).Offset(0, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next Nrng
BSStep = BSStep + 1
Next Brng
Application.ScreenUpdating = True
End Sub
I am going to post another question that I am looking for added on to this.
This would be in regards to if the value is not found, putting "NOTHING IN HISTORY FILE" in red in the cell.
Thanks again guys, would not have been able to find a solution without you pointing me in the right direction.
Here a few hints
You can store your headers in Array(), simplifying the code a lot:
Function rangeToArray(rng As Range) As Variant
rangeToArray = Application.Transpose(Application.Transpose(rng))
End Function
Sub CopyBlastSheetData()
headers = rangeToArray(ThisWorkbook.Worksheets("Blast List").Range("E1:Q1"))
'Rest of the code [..]
End Sub
Instead of repeating the same code define and use a Sub for copying and a Sub for pasting:
Sub copyFrom(ws As Worksheet, rng As Range, search As String)
ws.Select
rng.Select
Cells.Find(What:=search, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Selection.Copy
End Sub
Sub PasteTo(ws As Worksheet, rng As Range)
ws.Select
rng.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
And then use them on your code like this:
Call copyFrom(ws, Range("A1"), headers(1))
Call PasteTo(ws, Range("E3"))
This represent a good starting point.
I hope this helps.
I need to change the code so that
LMX220MA (KIT) becomes X220MA,
LMX220MA becomes X220MA,
LMX220 (KIT) becomes X220MB,
LMX220 becomes X220MB.
Tried removing LMX22 Selection.Replace line and then adding:
Range("H2").Select
ActiveCell.FormulaR1C1 = "=LEFT(RC[-1],6)"
Selection.Copy
Range("G1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(, 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks
Selection.Replace What:="LMX220", Replacement:="X220MB", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range("H2").Select
ActiveCell.FormulaR1C1 = "=LEFT(RC[-1],8)"
Selection.Copy
Range("G1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(, 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks
Selection.Replace What:="LMX220MA", Replacement:="X220MA",
LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
and so on.
Original code:
' Insert Model Number_Carrier column
Sheets("Data_Upload").Select
Columns("H:H").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("H1").Select
ActiveCell.FormulaR1C1 = "Model Number_Carrier"
' Fill Model Number_Carrier field
Range("H2").Select
ActiveCell.FormulaR1C1 = "=LEFT(RC[-1],5)"
Selection.Copy
Range("G1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(, 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Columns("H:H").Select
Selection.Replace What:="LMX21", Replacement:="X210MA", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="MW41M", Replacement:="_", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="Q710M", Replacement:="Q710MS", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="LMQ61", Replacement:="Q610MA", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="LMQ71", Replacement:="_", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="X410M", Replacement:="X410MK", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="LMX22", Replacement:="X220MB", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range("A1").Select
It will fill ModelNumber_Carrier cells with what is in the cell in Model column (LMX220 becomes LMX220) and "ModelNumber_Carrier" column becomes "Model" even though ModelNumber_Carrier column coding was left alone.
Returning compile error: end sub error when I change it to this:
Sub MPCSWeeklyReturnReason()
'
' MPCS_Return_Reason Macro
'
' Prevents screen refreshing.
Application.ScreenUpdating = False
' Check if procedure has already run
Dim rCell As String
rCell = ActiveSheet.Range("H1").Text
If InStr(1, rCell, "Model Number_Carrier") Then
Application.ScreenUpdating = True
MsgBox "Macro already run."
Exit Sub
Else
' Combine all worksheets to one for upload
Dim J As Integer
On Error Resume Next
Sheets(1).Select
Worksheets.Add
Sheets(1).Name = "Data_Upload"
Sheets(2).Activate
Range("A1").EntireRow.Select
Selection.Copy Destination:=Sheets(1).Range("A1")
For J = 2 To Sheets.Count
Sheets(J).Activate
Range("A1").Select
Selection.CurrentRegion.Select
Selection.Offset(1, 0).Resize(Selection.Rows.Count - 1).Select
Selection.Copy Destination:=Sheets(1).Range("A65536").End(xlUp)(2)
Next
' Insert Model Number_Carrier column
Sheets("Data_Upload").Select
Columns("H:H").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("H1").Select
ActiveCell.FormulaR1C1 = "Model Number_Carrier"
' Fill Model Number_Carrier field
Sub FindReplaceAll()
' This will find and replace text in all sheets
Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant
Dim fnd1 As Variant
Dim rplc1 As Variant
Dim fnd2 As Variant
Dim rplc2 As Variant
Dim fnd3 As Variant
Dim rplc3 As Variant
'Set the criteria to change here
fnd = "LMX220MA (KIT)"
rplc = "X220MA"
fnd1 = "LMX220MA"
rplc1 = "X220MA"
fnd2 = "LMX220 (KIT)"
rplc2 = "X220MB"
fnd3 = "LMX220"
rplc3 = "X220MB"
For Each sht In ActiveWorkbook.Worksheets
sht.Cells.Replace what:=fnd, Replacement:=rplc, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
sht.Cells.Replace what:=fnd1, Replacement:=rplc1, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
sht.Cells.Replace what:=fnd2, Replacement:=rplc2, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
sht.Cells.Replace what:=fnd3, Replacement:=rplc3, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next sht
End Sub
' ESN Concantenate Fix
Range("Q2").Select
ActiveCell.FormulaR1C1 = "=TEXT(,RC[-11])"
Selection.Copy
Range("A2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 16).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Range("R2").Select
ActiveCell.FormulaR1C1 = "=IF(ISERROR(RC[-1]), RC[-12], RC[-1])"
Selection.Copy
Range("Q2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.Copy
Range("F2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Columns("Q:R").Select
Selection.Delete Shift:=xlToLeft
Range("A1").Select
' TRIM Reason and SUBReason spaces
Range("Q2").Select
ActiveCell.FormulaR1C1 = "=TRIM(RC[-4])"
Selection.Copy
Range("A2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 16).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.Copy
Range("M2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Columns("Q:Q").Select
Selection.Delete Shift:=xlToLeft
Range("A1").Select
' Enables screen refreshing.
Application.ScreenUpdating = True
' Save the Workbook
ActiveWorkbook.Save
End If
End Sub
Here try this. It will go through all of the sheets in your workbook and find and replace all cases with the text you specified. I was unsure if you wanted to have the "(KIT)" included so I left it in, but feel free to adjust as necessary.
Sub FindReplaceAll()
' This will find and replace text in all sheets
Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant
Dim fnd1 As Variant
Dim rplc1 As Variant
Dim fnd2 As Variant
Dim rplc2 As Variant
Dim fnd3 As Variant
Dim rplc3 As Variant
'Set the criteria to change here
fnd = "LMX220MA (KIT)"
rplc = "X220MA"
fnd1 = "LMX220MA"
rplc1 = "X220MA"
fnd2 = "LMX220 (KIT)"
rplc2 = "X220MB"
fnd3 = "LMX220"
rplc3 = "X220MB"
For Each sht In ActiveWorkbook.Worksheets
sht.Cells.Replace what:=fnd, Replacement:=rplc, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
sht.Cells.Replace what:=fnd1, Replacement:=rplc1, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
sht.Cells.Replace what:=fnd2, Replacement:=rplc2, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
sht.Cells.Replace what:=fnd3, Replacement:=rplc3, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next sht
End Sub
Took another look at this and you can also do it this way by using arrays. Similar to my other answer with this one if I left in the "(KIT)" that shouldn't have been there or anything just adjust as necessary but the syntax is there.
Sub FindReplaceAll()
Dim sht As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long
'Set the criteria to change here
fndList = Array("LMX220MA (KIT)", "LMX220MA", "LMX220 (KIT)", "LMX220")
rplcList = Array("X220MA", "X220MA", "X220MB", "X220MB")
'Loop through each item in Array lists
For x = LBound(fndList) To UBound(fndList)
'Loop through each worksheet in ActiveWorkbook
For Each sht In ActiveWorkbook.Worksheets
sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next sht
Next x
End Sub
I can't get the values I enter into column D to be sorted by ascending order.
Sheets("Template").Select
Range("A2").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Sheets("OutPut").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.Sort Key1:=Range("D1"), Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortTextAsNumbers```
Perhaps like this?
Sub tgr()
Dim wb As Workbook
Dim wsTemplate As Worksheet
Dim wsOutput As Worksheet
Dim rCopy As Range
Set wb = ActiveWorkbook
Set wsTemplate = wb.Worksheets("Template")
Set wsOutput = wb.Worksheets("OutPut")
Set rCopy = wsTemplate.Range("A2", wsTemplate.Cells.SpecialCells(xlCellTypeLastCell))
With wsOutput.Range("A1").Resize(rCopy.Rows.Count, rCopy.Columns.Count)
.Value = rCopy.Value
.Sort Intersect(.Cells, .Parent.Columns("D")), xlAscending, Header:=xlYes, OrderCustom:=1, DataOption1:=xlSortTextAsNumbers
End With
End Sub
I have sheets with names such as M&MFIN.NS, M&M.NS, L&TFH.NS, i'm trying to find one of them and then do the specific task.
However, if one of the above mentioned sheet is not found, the code terminates(Exit Sub).
i need help, if sheet not found it should go to next search option, and then rest of the code
Please guide
Sub SearchSheetNameandcreatenewsheet()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim sName As String
Dim sFound As Boolean
sName = "M&MFIN.NS"
If sName = "" Then Exit Sub
sFound = False
On Error Resume Next
ActiveWorkbook.Sheets(sName).Select
Range(Range("E3"), Range("E3").End(xlDown)).Select
Selection.Copy
Worksheets("Close Price").Activate
Cells.Find(What:="M&MFIN.NS", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(1, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Dim sName1 As String
Dim sFound1 As Boolean
sName1 = "M&M.NS"
If sName1 = "" Then Exit Sub
sFound1 = False
On Error Resume Next
ActiveWorkbook.Sheets(sName1).Select
Range(Range("E3"), Range("E3").End(xlDown)).Select
Selection.Copy
Worksheets("Close Price").Activate
Cells.Find(What:="M&M.NS", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(1, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Dim sName2 As String
Dim sFound2 As Boolean
sName2 = "L&TFH.NS"
If sName2 = "" Then Exit Sub
sFound2 = False
On Error Resume Next
ActiveWorkbook.Sheets(sName2).Select
Range(Range("E3"), Range("E3").End(xlDown)).Select
Selection.Copy
Worksheets("Close Price").Activate
Cells.Find(What:="L&TFH.NS", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(1, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").CurrentRegion.Select
Selection.Replace What:="null", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'"creating close price sheet seperataly"
Sheets("Close Price").Select
Sheets("Close Price").Copy
ChDir "C:\Lookback Momentum Analysis"
ActiveWorkbook.SaveAs Filename:= _
"C:\Lookback Momentum Analysis\Close Price.xlsx", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
ActiveWindow.Close
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Worksheets("Parameters").Activate
End Sub
This would be an option:
Option Explicit
Sub SearchSheetNameandcreatenewsheet()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim wb As Workbook, ws As Worksheet
Set wb = ThisWorkbook 'the workbook which has the code
For Each ws In wb.Worksheets
Select Case ws.Name
Case "M&MFIN.NS"
'code
Case "M&M.NS"
'code
Case "L&TFH.NS"
'code
End Select
Next ws
End Sub
You only need to feed the sheet names and introduce your code below every Case for especific worksheet names.
I'm new with VBA for excel and asking for your expertise.
I made a recording Marco witch works totaly fine, the problem is that I know it can be shorter and look more nicer, and maybe go even faster to run.
I've read that the .Select shall be avoided as much as possible, and when recording Macros, it does this automatically.
Sub Audit_chat()
Range("R13").Select
Selection.Copy
Range("F2:K2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "[h]:mm:ss"
Columns("F:K").Select
Selection.Replace What:="No Value", Replacement:="0", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range("B:B,C:C,N:N,O:O").Select
Range("O1").Activate
Selection.Copy
Sheets("Agents").Select
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveSheet.Range("$A$1:$D$1048575").RemoveDuplicates Columns:=Array(1, 2), _
Header:=xlYes
Columns("D:D").Select
Selection.Copy
Range("C1").Select
ActiveSheet.Paste
Sheets("Counter").Select
Range("A1").Select
End Sub
Can this be fixed, or am I "doomed" for life? :)
Explaination of what it does.
Range("R13").Select
Selection.Copy
'' Copy a blank cell
Range("F2:K2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
'' Select Range F2:K2 all the way to the end of the columns
Selection.NumberFormat = "[h]:mm:ss"
'' set the numbers to [h]:mm:ss
Reason: The file I has have the cells in the wrong format, and even if I change the format, It will not update, but I found out that If I copied a blank cell over it as a special paste with "Value" and "Add" it fixed the problem.
Columns("F:K").Select
Selection.Replace What:="No Value", Replacement:="0", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'' In Colums F:K find and replace "No Value" (Text) to "0"
Range("B:B,C:C,N:N,O:O").Select
Range("O1").Activate
Selection.Copy
Sheets("Agents").Select
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
'' Copy all data in B:B,C:C,N:N,O:O, and paste it in Sheet "Agents"
ActiveSheet.Range("$A$1:$D$1048575").RemoveDuplicates Columns:=Array(1, 2), _
Header:=xlYes
'' Remove duplicates in all cells A:D and has a header
Columns("D:D").Select
Selection.Copy
Range("C1").Select
ActiveSheet.Paste
'' Copy the all the information from colum D and paste it in C
Sheets("Counter").Select
Range("A1").Select
'' Go to Sheet "Counter"
Thanks in advance.
Best Regards,
Peter
Writing code like the macro recorder will be a nightmare to maintain.
Here's my attempt at a cleanup (Far, far from perfect)(untested);
Sub x()
'///////////////////
'// First Action //
'/////////////////
Range("R13").Select
Selection.Copy
Range("F2:K2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "[h]:mm:ss"
'// Try //
Sheets("MySheet").[F2:K2].Value = [R13].Value
Sheets("MySheet").[F2:K2].NumberFormat = "[h]:mm:ss"
'////////////////////
'// Second Action //
'//////////////////
Columns("F:K").Select
Selection.Replace What:="No Value", Replacement:="0", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'// Try //
Sheets("MySheet").[F:K].Replace What:="No Value", Replacement:="0", LookAt:=xlPart
'///////////////////
'// Third Action //
'/////////////////
Range("B:B,C:C,N:N,O:O").Select
Range("O1").Activate
Selection.Copy
Sheets("Agents").Select
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveSheet.Range("$A$1:$D$1048575").RemoveDuplicates Columns:=Array(1, 2), _
Header:=xlYes
'// Try //
Sheets("MySheet").Range("B:B,C:C,N:N,O:O").Copy Sheets("Agents").[A1]
Sheets("Agents").[A:D].RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
'////////////////////
'// Fourth Action //
'////////////////////
Columns("D:D").Select
Selection.Copy
Range("C1").Select
ActiveSheet.Paste
Sheets("Counter").Select
Range("A1").Select ' I think this only exists to go back to where you started
'// Try //
Sheets("Mysheet").[D:D].Copy [C:C]
'////////////////////////
'// So, total code is //
'//////////////////////
Sheets("MySheet").[F2:K2].Value = [R13].Value
Sheets("MySheet").[F2:K2].NumberFormat = "[h]:mm:ss"
Sheets("MySheet").[F:K].Replace What:="No Value", Replacement:="0", LookAt:=xlPart
Sheets("MySheet").Range("B:B,C:C,N:N,O:O").Copy Sheets("Agents").[A1]
Sheets("Agents").[A:D].RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
Sheets("Mysheet").[D:D].Copy [C:C]
End Sub
If you activate/select a cell/sheet to manipulate it, you're doing yourself a disservice, you should never need to*
* = Unless the macro/code is to specifically access a cell/sheet of interest (Like a "go to agents list sheet" button or something)
Whew! That is some ugly code. When you record a macro the result isn't easy to read.
Can you tell me what you're trying to do? That will help me to clean-up your code.
".Activate" vs. ".Select"
Also here is the layman's explanation on the difference between "Activate" and "Select":
With ".Select", for example worksheets, you can have more than one worksheet selected. ".Select" allows you to conduct operations on multiple objects at one time.
With ".Activate", for example worksheets, only allows you to have one worksheets active at a time. So in the below code you will have three worksheets that are selected but only one activated.
Worksheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Worksheets("Sheet2").Activate
In the below code you will only have one worksheet selected.
Worksheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Worksheets("Sheet2").Select
The reason why ".Select" can get you in trouble is because if you select several objects you will conduct operations on all of the objects you select. You may or may not want that. Using ".Activate" limits your operations to only one object.
Solution 01
Below is the first attempt at a solution. In general I would recommend using the VBA objects and Excel objects to your advantage and comment the code well. Below is one option on how to do that.
The code is longer but it is clearer and much easier to understand while taking advantage of the VBA / Excel object library.
I have not tested the below code.
Sub Audit_chat()
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' variables / object declaration
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' declare objects
Dim wks_dest As Worksheet, wks_source As Worksheet
Dim rng_srce_copy_01 As Range, rng_dest_01 As Range, rng_srce_copy_02 As Range
Dim rng_dest_dup_01 As Range, rng_srce_copy_03 As Range
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' variables / object initialzation
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' set worksheet objects
' I don't know the name of the source worksheet
Set wks_source = Worksheets("<Source Worksheet Name>")
Set wks_dest = Worksheets("Agents")
' set source range objects
Set rng_srce_copy_01 = wks_source.Range("R13")
Set rng_srce_copy_02 = wks_source.Range("O1")
Set rng_srce_copy_03 = wks_dest.Range("D:D")
' set desstination range objects
Set rng_dest_01 = wks_source.Range("F:K")
Set rng_dest_dup_01 = wks_dest.Range("$A$1:$D$1048575")
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
' start main method
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' copy the source 01
rng_srce_copy_01.Copy
' paste information from range_srce_copy_01
With rng_dest_01
.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlAdd, _
SkipBlanks:=False, _
Transpose:=False
' change cell format
.NumberFormat = "[h]:mm:ss"
' replace "No Value" with 0
.Replace What:="No Value", _
Replacement:="0", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
End With
' application mode turn off
Application.CutCopyMode = False
' copy source 02
' this will only copy one cell "O1" which is what your code is doing
' if you want to copy columns B, D, N, O then you need to define your
' range objct as:
' Set rng_srce_copy_02 = Range("B:B,C:C,N:N,O:O")
' this is where Select vs. Activate gets you in trouble
' do you want all the colums or just cell?
rng_srce_copy_02.Copy
' go to destination worksheet
' you may have to break this up into:
' wks_dest.Activate
' Range("A1").Activate
' but I don't think so
wks_dest.Range("A1").Activate
wks_dest.Paste
' application mode turn off
Application.CutCopyMode = False
' look at all the cells in the first two columns and remove
' the duplicates
rng_dest_dup_01.RemoveDuplicates Columns:=Array(1, 2), _
Header:=xlYes
' copy range 03
rng_srce_copy_03.Copy
' paste at cell C1
Range("C1").Select
wks_dest.Paste
' go to "Counter" worksheet
Worksheets("Counter").Activate
Range("A1").Activate
End Sub
you can try to "Join" the range("").select with the next line, for example
Range("R13").Select
Selection.Copy
Can be:
Range("R13").Copy
Try this:
Sub Audit_chat()
Range("R13").Copy
Range("F2:K2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks _
:=False, Transpose:=False
Selection.NumberFormat = "[h]:mm:ss"
Columns("F:K").Replace What:="No Value", Replacement:="0", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range("O1").Copy
Sheets("Agents").Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveSheet.Range("$A$1:$D$1048575").RemoveDuplicates Columns:=Array(1, 2), _
Header:=xlYes
Columns("D:D").Copy
Range("C1").Select
ActiveSheet.Paste
Sheets("Counter").Range("A1").Select
End Sub