Loop VBA All Sheet Except MasterSheet - excel

My code is
Sub Macro5()
'
' Macro5 Macro
'
Range("A7").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Columns.AutoFit
Range("A8").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R4C2"
Range("A8").Select
Selection.Copy
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
Range("A7").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.AutoFilter
Selection.Columns.AutoFit
ActiveWindow.SmallScroll ToRight:=15
ActiveSheet.Range("$A$7:$AC$38").AutoFilter Field:=20, Criteria1:="0"
ActiveSheet.Range("$A$7:$AC$38").AutoFilter Field:=22, Criteria1:="0"
ActiveWindow.SmallScroll ToRight:=-45
Range("A13").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.EntireRow.Delete
Cells.Select
Range("A22").Activate
Selection.AutoFilter
Range("A11").Select
Columns("E:E").Select
Application.CutCopyMode = False
Selection.Replace What:="Discovery Ads", Replacement:="Qua" & ChrW(777) & "ng Ca" & ChrW(769) & "o Kha" _
& ChrW(769) & "m Pha" & ChrW(769) _
, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat _
:=False, ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
Columns("E:E").Select
Selection.Replace What:="Product Search Ad", Replacement:= _
"Qua" & ChrW(777) & "ng Ca" & ChrW(769) & "o Ti" _
& ChrW(768) & "m Kiê" & ChrW(769) & "m Sa" & ChrW(777) & "n Phâ" & ChrW( _
777) & "m", LookAt:=xlPart, SearchOrder:=xlByRows, _
MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False, _
FormulaVersion:=xlReplaceFormula2
Columns("E:E").Select
Selection.Replace What:="Shop Search Ad", Replacement:= _
"Qua" & ChrW(777) & "ng Ca" & ChrW(769) & "o Ti" _
& ChrW(768) & "m Kiê" & ChrW(769) & "m Shop", LookAt:=xlPart, SearchOrder:=xlByRows, _
MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False, _
FormulaVersion:=xlReplaceFormula2
Selection.AutoFilter
End Sub
So i have insert this code before code
Dim ws As Worksheet
For Each ws In Sheets
And insert more prepend every Range...Select like
ws.Range("A7").Select
But it not work for me. So is there any other way to do it?. Loop VBA all sheet in that workbook except "MasterSheet"
About my data it look like this :
enter image description here
So i wanna change A7:A end down is value B4.
-Then filter, Filter column T,V every value = 0 and delete it
Replace some name
And this is final after run marco 1 sheet :
enter image description here
enter image description here

This is how I would normally loop through all sheets with an exception:
Sub loop_through_sheets()
Dim ws As Worksheet
For Each ws In Sheets
If ws.Name <> "Mastersheet" Then
'... run the code on ws
Else
'.. do nothing
End If
Next
End Sub
Your code to run on ws might look something like this:
With ws
'auto fit the columns
.Range("A:AC").Columns.AutoFit
'find the last populated cell in column A
Dim lastrow as Long
lastrow=ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'insert the formula
.Range("A8:A" & lastrow).FormulaR1C1 = "=R4C2"
'etc. etc.
End with

of course this is not the cleanest and best solution (see comment "avoid select...."), but leave the code as is it, make a sub for calling it like:
sub callmymacro
Dim ws As Worksheet
For Each ws In Sheets
if ws.Name = "Mastersheet" GoTo notthisone
Sheets(ws).Select
call Macro5
notthisone:
Next
end sub

Related

VBA Loop For Each Worksheet

I am working on code to basically go through each sheet in my Workbook, and then selection delete and at finish save all worksheets to csv. I don't receive any errors, but it also only save worksheets.
Any help is greatly appreciated!
Public Sub SaveWorksheetsAsCsv()
Dim xWs As Worksheet
Dim xDir As String
Dim folder As FileDialog
Set folder = Application.FileDialog(msoFileDialogFolderPicker)
If folder.Show <> -1 Then Exit Sub
xDir = folder.SelectedItems(1)
For Each xWs In Application.ActiveWorkbook.Worksheets
With xWs
Range("A3").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Range("AU1").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Columns("A:AT").Select
Range("AT1").Activate
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Range("A1").Select
Cells.Replace What:="(puste)", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
End With
xWs.SaveAs Filename:=xDir & "\" & xWs.Name, FileFormat:=xlCSV, Local:=True
Next
End Sub
When using With prefix ranges with a dot.
Option Explicit
Public Sub SaveWorksheetsAsCsv()
Dim xWs As Worksheet, xDir As String, msg As String
Dim folder As FileDialog
Set folder = Application.FileDialog(msoFileDialogFolderPicker)
If folder.Show <> -1 Then Exit Sub
xDir = folder.SelectedItems(1)
Application.ScreenUpdating = False
For Each xWs In Application.ActiveWorkbook.Worksheets
With xWs
msg = msg & vbCrLf & xWs.Name
.Range(.Range("A3"), .Range("A3").End(xlToRight).End(xlDown)).Copy
.Range("AU1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
.Columns("A:AT").Delete Shift:=xlToLeft
.UsedRange.Cells.Replace What:="(puste)", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False ', FormulaVersion:=xlReplaceFormula2
.SaveAs Filename:=xDir & "\" & .Name, FileFormat:=xlCSV, Local:=True
'.Activate ' optional
'.Range("A1").Select ' optional
End With
Next
Application.ScreenUpdating = True
MsgBox "Sheets saved :" & msg, vbInformation
End Sub

VBA Last Row errors

I'm using this code, but columns with last row (A,B,K,L) fill in with 0 beyond the defined last row. Additionally, my transaction and type occasionally stop working, but if anyone sees what i'm doing wrong i'd love to learn so i don't have this issue again.
Sub test()
Dim lastRow As Long
lastRow = Cells(Rows.Count, 10).End(xlUp).Row
'delete blank columns
Range("W:W,U:U,S:S,Q:Q,O:O,M:M,K:K,I:I,G:G,E:E,C:C,A:A").Select
Range("A1").Activate
Selection.Delete Shift:=xlToLeft
'filter for blanks
Range("A:L").CurrentRegion.Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$L$1").AutoFilter Field:=10, Criteria1:="="
ActiveSheet.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
Selection.AutoFilter
'Trans
Columns("A:A").Select
Selection.NumberFormat = "General"
Range("A2:A" & lastRow).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
Columns("A:A").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Type
Columns("B:B").Select
Selection.NumberFormat = "General"
Range("B2:B" & lastRow).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
Columns("B:B").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Debit
Range("K2:K" & lastRow).Select
'Range(Selection, Selection.End(xlDown)).Select
Selection.Replace What:="", Replacement:="0", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'credit
Range("L2:L" & lastRow).Select
'Range(Selection, Selection.End(xlDown)).Select
Selection.Replace What:="", Replacement:="0", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
So sorry for my English, just get you wrong 😆
Try to use cycle instead of replace.
Use Dim EmptCell as range once.
Dim EmptCell as range
For Each EmptCell in Range("youRange").Cells
If EmptCell.value = "" Then EmptCell.value = 0
Next EmptCell
And try to not to use selection. Work directly with a ranges, or use variables like you did with LastRow.
Small example below.
' Trans
Columns("A:A").NumberFormat = "General"
Range("A2:A" & lastRow).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
Columns("A:A").value = Columns("A:A").value
And I'm definitely recommend to change LastRow algorithm to this bulletproof one.
© https://stackoverflow.com/a/11169920/12882709
With Sheets("Sheet1")
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If

Loop to search data in workbook1, copy offset cell to workbook2

I need a loop to copy cells offset from a found value in SOURCE, (based on range in DESTINATION) to DESTINATION.
In this case I want to copy value from SOURCE ("K10") to DESTINATION ("G5"), after value ("E10") found in SOURCE based on value ("H5") in DESTINATION.
I need to search for all values in DESTINATION ("H:H").
Book_source.xlsx
Book_destination.xlsx
My recorded code:
Windows("Book_destination.xlsx").Activate
Dim rng As Variant
rng = Range("H5").Value
rng.Select
Selection.Copy
Application.WindowState = xlNormal
Windows("Book_source.xlsx").Activate
Cells.Find(What:=rng, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(0, 6).Select
Application.CutCopyMode = False
Selection.Copy
Windows("Book_destination.xlsx").Activate
Range("G5").Select
ActiveSheet.Paste
I created this code and is working for me.
For anyone interested
Thanks all of you. :)
Enjoy, it's free!
I'm glad to share this.
Sub part_of_code()
Dim i As Integer
i = 2
'calling LastRow
Call LastRecord(LastRow)
For i = i To LastRow
On Error Resume Next
'Application.WindowState = xlNormal
Range("H" & i).Select
Selection.Copy
Dim rng As Variant
rng = Range("H" & i)
Workbooks("Book2.xlsx").Worksheets("Sheet1").Activate
Cells.Find(What:=rng, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(0, 6).Select
Application.CutCopyMode = False
Selection.Copy
Workbooks("Book1.xls").Worksheets("Sheet2").Activate
Range("H" & i).Offset(0, -1).Select
ActiveSheet.Paste
Next i
End Sub
Private Sub LastRecord(LastRow)
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
End Sub

Compile Error: Syntax Error caused by code inserting a excel formula

This Line of Code causes a Compile Error: Syntax Error
I cant figure out what i have to change. It works fine with other formulas so i think it may be something about the formula.
Range("O2:O" & LastRow).Formula = "=WENN(Q2="";"";WENN(H2*7*Q2<L2;"Möglich";"Prüfen"))"
Thanks for help and suggestions
My entire code:
Columns("A:M").Select
Selection.Replace What:=",", Replacement:=".", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range("N2").Select
Range("P2:P240023").Select
Application.CutCopyMode = False
Selection.ClearContents
Range("N3").Select
Range("N3:O24023").Select
Selection.ClearContents
Range("N2:O2").Select
Selection.AutoFill Destination:=Range("N2:O24023")
Range("N2:O240023").Select
Columns("A:O").Select
Columns("A:O").EntireColumn.AutoFit
Range("C:C,J:J,K:K,M:M").Select
Range("M1").Activate
Selection.EntireColumn.Hidden = True
Rows("2:2").Select
ActiveWindow.FreezePanes = True
Range("O2:O" & LastRow).Formula = "=WENN(Q2="";"";WENN(H2*7*Q2<L2;"Möglich";"Prüfen"))"
The problem is that there aren't enough quotes " on the first part of the formula, causing the string to not terminate. Try to change the code like this:
Range("O2:O" & lastRow).Formula = "=IF(Q2="""","""",IF(H2*7*Q2<L2,""Möglich"",""Prüfen""))"
Or like this if you want to keep your local language formula:
Range("O2:O" & lastRow).FormulaLocal = "=WENN(Q2="""";"""";WENN(H2*7*Q2<L2;""Möglich"";""Prüfen""))"
Hope it helps.
When you use formulas "" (Empty) should be """" and "test" should be ""test""
Change this:
Range("O2:O" & LastRow).Formula = "=WENN(Q2="";"";WENN(H2*7*Q2<L2;"Möglich";"Prüfen"))"
To this:
Sheet1.Range("O2:O" & LastRow).Formula = "=WENN(Q2="""";"""";WENN(H2*7*Q2<L2,""Möglich"",""Prüfen""))"
If needed also change ";" to "," (depends on excel version).
Full Code:
Option Explicit
Sub test()
Dim LastRow As Long
With ThisWorkbook.Worksheets("Sheet1") '<- Change sheet name if needed
LastRow = .Cells(.Rows.Count, "O").End(xlUp).Row '<- Change column lf needed. Have in mind that because Lastrow is in the with statement, Lastrow calculation related with the sheet in the with statemet
.Columns("A:M").Replace What:=",", Replacement:=".", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
.Range("N3:O24023,P2:P240023").ClearContents '<- ClearContents clear only Contents . if you want to clear everything use .Clear
.Range("N2:O2").AutoFill Destination:=Range("N2:O24023")
.Columns("A:O").EntireColumn.AutoFit
.Range("C:C,J:J,K:K,M:M").EntireColumn.Hidden = True
Rows("2:2").Select
ActiveWindow.FreezePanes = True
.Range("O2:O" & LastRow).Formula = "=IF(Q2="""",IF((H2*7*Q2)<L2,""Möglich"",""Prüfen""))"
End With
End Sub

Error putting a variable inside excel VBA function

Sub airtableCleaner()
Dim x As Integer
Dim argCounter As Integer
Dim A As String
Dim B As String
Dim folderLocation As Variant
Dim Answer As VbMsgBoxResult
'Ask user if they want to run macro
Answer = MsgBox("Do you want to run this macro? Please use airtable Download as CSV - Column 1: Primary key, Column 2: Airtable Linkz", vbYesNo, "Run Macro")
If Answer = vbYes Then
folderLocation = Application.InputBox("Enter a folder location where your image assets will be")
'Cleanup to just amazons3 dl.airtable links
Columns("B:B").Select
Selection.Replace What:="* ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="(", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:=")", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'Count Cells
Range("B2").Activate
Do
If ActiveCell.Value = "" Then Exit Do
ActiveCell.Offset(1, 0).Activate
argCounter = argCounter + 1
Loop
'Copy Image Links to new cells to format in Column C
Columns("B:B").Select
Selection.Copy
Columns("C:C").Select
ActiveSheet.Paste
Application.CutCopyMode = False
'Clean up links to only have names in Column C
Selection.Replace What:="https://dl.airtable.com/", Replacement:="", _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:= _
False, ReplaceFormat:=False
'Create Batch on Column D
Range("D2").Select
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(""COPY "",CHAR(34),RC[-1],CHAR(34),"" "", CHAR(34), [" & folderLocation & "],RC[-3],"".png"",CHAR(34))"
Range("D2").Select
Selection.AutoFill Destination:=Range("D2:D9")
Range("D2:D9").Select
'Delete header row 1 information
Rows("1:1").Select
Selection.Delete Shift:=xlUp
'Repaste values back into column D removing formulas
Columns("D:D").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
End If
End Sub
I have this set of excel VBA code. I'm getting an error
Run-time error '1004' Application-defined or object-defined error
At this line
"=CONCATENATE(""COPY "",CHAR(34),RC[-1],CHAR(34),"" "", CHAR(34), [" & folderLocation & "],RC[-3],"".png"",CHAR(34))"
I have been setting folderLocation variable value as c:\doge and making a file folder reflecting this
My code was working fine until I introduced a variable inside of an excel function
What am I doing wrong here?
EDIT
this was the original formula I was using
=CONCATENATE("COPY ",CHAR(34),C5,CHAR(34)," ", CHAR(34), "c:\doge\",A5,".png",CHAR(34))
where c:\doge\ was the place I wanted to input the user input at.
Is this what you are trying?
folderLocation = "c:\doge\"
Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34),C5,CHAR(34),"" "", CHAR(34), " & _
Chr(34) & folderLocation & Chr(34) & ",A5,"".png"",CHAR(34))"

Resources