If file is not open go to next - vba

From multiple workbooks I copy info into one Workbook. This works like a charm. I just got informed that in a few weeks I'll have to add another file to copy data from. I wanted to get the Macro going now but if I don't have the new workbook open the macro gets stuck. I have tried a few different ways but I don't get it to work.
I have the same code going with the other 3 workbooks, so when this comes I want the macro to skip it if Workbook is not open.
Any suggestions?
Windows("filename.xlsx").Activate
Range(Range("A2:K2"), Range("A2:K2").End(xlDown)).Copy
Workbooks("Masterfile.xlsm").Sheets("Electra").Activate
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

This code will step through the workbooks that you have open and check against a list of file names that you need.
There's a couple of problems that could occur:
Your workbook must have a sheet called Sheet1 as the code doesn't check for this.
If you have a file called book1.xlsm and 1book1.xlsm. book1.xlsm occurs in both.
Finding the last cell in columns A:K could be improved. Currently it will go from A2 to the last row containing data in column K.
All information will be pasted starting at cell A2. You need code to find the last row on the Electra sheet as well.
Sub Test()
Dim sFileNames As String
Dim wrkBk As Workbook
sFileNames = "Somebook.xls, book1.xlsm, book2.xlsx"
For Each wrkBk In Workbooks
If InStr(UCase(sFileNames), UCase(wrkBk.Name)) > 0 Then
With wrkBk.Worksheets("Sheet1")
.Range(.Cells(2, 1), .Cells(.Rows.Count, 11).End(xlUp)).Copy
ThisWorkbook.Worksheets("Electra").Range("A2").PasteSpecial xlPasteValues
End With
End If
Next wrkBk
End Sub
Edit:
To paste to different sheets in the MasterFile one option is to use a dictionary to hold workbook & destination sheet pairings.
This code will add the file names as keys and the destination sheets as values. It then checks if the workbook name exists within the dictionary, if it does it copies the data from Sheet1 and pastes the values into relevant sheet.
Sub Test()
Dim dict As Object
Dim wrkBk As Workbook
Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
dict.Add "Book2.xlsx", "Sheet1"
dict.Add "Book3.xlsx", "Sheet2"
For Each wrkBk In Workbooks
If dict.exists(wrkBk.Name) Then
With wrkBk.Worksheets("Sheet1")
.Range(.Cells(2, 1), .Cells(.Rows.Count, 11).End(xlUp)).Copy
ThisWorkbook.Worksheets(dict(wrkBk.Name)).Range("A2").PasteSpecial xlPasteValues
End With
End If
Next wrkBk
End Sub
Edit 2:
If the source workbooks are all closed at the start then use this code to open the relevant files, copy the info and close the file again.
Sub Test()
Dim dict As Object
Dim wrkBk As Workbook
Dim vItem As Variant
Dim sPath As String
'All workbooks to open will be in this folder.
'Remember to include the final back-slash (\).
sPath = "C:\Test\"
Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
'If files will not all be in the same folder, then
'full file path must be included here and remove
'references to sPath variable in the code.
dict.Add "Book2.xlsx", "Sheet1"
dict.Add "Book3.xlsx", "Sheet2"
For Each vItem In dict
Set wrkBk = Workbooks.Open(sPath & vItem)
With wrkBk.Worksheets("Sheet1")
.Range(.Cells(2, 1), .Cells(.Rows.Count, 11).End(xlUp)).Copy
ThisWorkbook.Worksheets(dict(wrkBk.Name)).Range("A2").PasteSpecial xlPasteValues
End With
wrkBk.Close SaveChanges:=False
Next vItem
End Sub

This is maybee the most good looking but it actually worked, I never done Call before so I just had to try. I can run this multiple time with different books open and it don't bug out or mess things up. As faar as two test are made.
Sub Steg11()
'
' Steg1 Macro
' Macrot flyttar data från CDPPT fil med försäljningsdata,
' från fil med Electras försäljning och fil med produktdata.
' Kopierar formler, rensar försäljning till Lagerhållare
Dim MainWkbk As Workbook
Dim NextWkbk As Workbook
Set MainWkbk = ActiveWorkbook
Set NextWkbk = ActiveWorkbook
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
' Letar in CDPPT, lägger in formler, sorterar bladet.
On Error GoTo 3
Windows("CDPPT.xlsx").Activate
Range(Range("A2"), Range("A2").End(xlToRight).End(xlDown)).Copy
Workbooks("Datamatchningsfil.xlsm").Sheets("CDPPT").Activate
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("CDPPT").Select
Range(Range("I2"), Range("I2").End(xlToRight)).Copy
Range("H2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Offset(1, 0).Select
ActiveSheet.Paste
Application.Goto Sheets("CDPPT").Range("A:M")
Selection.Sort Key1:=Range("E1"), Order1:=xlDescending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
'Tar bort data där telia inte ska betala skatt
Application.Goto Sheets("CDPPT").Range("E1")
ActiveSheet.Range("$A:$M").AutoFilter Field:=5, Criteria1:="=*BRIGHTSTAR*" _
, Operator:=xlAnd
ActiveCell.Offset(1, 0).Activate
Range(Selection, Selection.End(xlDown)).Select
Selection.EntireRow.Delete
ActiveSheet.ShowAllData
ActiveWorkbook.RefreshAll
ActiveSheet.Range("$A:$M").AutoFilter Field:=5, Criteria1:="=*ELECTRA*" _
, Operator:=xlAnd
ActiveWindow.SmallScroll Down:=-6
ActiveCell.Offset(1, 0).Activate
Range(Selection, Selection.End(xlDown)).Select
Selection.EntireRow.Delete
ActiveSheet.ShowAllData
ActiveWorkbook.RefreshAll
ActiveSheet.Range("$A:$M").AutoFilter Field:=5, Criteria1:="=*Ingram*" _
, Operator:=xlAnd
ActiveWindow.SmallScroll Down:=-9
ActiveCell.Offset(1, 0).Activate
Range(Selection, Selection.End(xlDown)).Select
Selection.EntireRow.Delete
ActiveSheet.ShowAllData
ActiveWorkbook.RefreshAll
ActiveSheet.Range("$A:$M").AutoFilter Field:=3, Criteria1:="=*brev*" _
, Operator:=xlAnd
ActiveCell.Offset(1, 0).Activate
Range(Selection, Selection.End(xlDown)).Select
Selection.EntireRow.Delete
ActiveSheet.ShowAllData
ActiveWorkbook.RefreshAll
ActiveSheet.Range("$A:$M").AutoFilter Field:=3, Criteria1:="=*Konfig*" _
, Operator:=xlAnd
ActiveCell.Offset(1, 0).Activate
Range(Selection, Selection.End(xlDown)).Select
Selection.EntireRow.Delete
ActiveSheet.ShowAllData
ActiveWorkbook.RefreshAll
ActiveSheet.Range("$A:$M").AutoFilter Field:=5, Criteria1:="=*(Manuellt
inmatad)*" _
, Operator:=xlAnd
ActiveCell.Offset(1, 0).Activate
Range(Selection, Selection.End(xlDown)).Select
Selection.EntireRow.Delete
ActiveSheet.ShowAllData
ActiveWorkbook.RefreshAll
3
Call Produktdata
End Sub
Sub Produktdata()
'Letar in produktdata
On Error GoTo 4
Windows("Produktdata.xlsx").Activate
If ActiveSheet.AutoFilterMode Then Cells.AutoFilter
Range(Range("A:J"), Range("A:J").End(xlDown)).Copy
Workbooks("Datamatchningsfil.xlsm").Sheets("Produktdata").Activate
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
4
Call Electra
End Sub
Sub Electra()
'Letar in data från Lagerhållare
On Error GoTo 5
Windows("Electra sales.xlsx").Activate
Range(Range("A2:K2"), Range("A2:K2").End(xlDown)).Copy
Workbooks("Datamatchningsfil.xlsm").Sheets("Electra").Activate
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
5
Call TalkTelecom
End Sub
Sub TalkTelecom()
'Letar in data från Lagerhållare
On Error GoTo 6
Windows("TalkTelecom.xlsx").Activate
Range(Range("A2:K2"), Range("A2:K2").End(xlDown)).Copy
Workbooks("Datamatchningsfil.xlsm").Sheets("TalkTelecom").Activate
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
6
Call Techdata
End Sub
Sub Techdata()
'Letar in data från Lagerhållare
On Error GoTo 7
Windows("TechData.xlsx").Activate
Range(Range("A2:K2"), Range("A2:K2").End(xlDown)).Copy
Workbooks("Datamatchningsfil.xlsm").Sheets("TechData").Activate
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
7
Call Continue
End Sub
Sub Continue()
' Utför text till kolumn
Application.Goto Sheets("Produktdata").Range("C:C")
Columns("C:C").Select
Selection.TextToColumns Destination:=Range("C1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Application.Goto Sheets("CDPPT").Range("F:F")
Columns("F:F").Select
Selection.TextToColumns Destination:=Range("F1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Application.Calculation = xlCalculationAutomatic
ActiveWorkbook.RefreshAll
'Lägger in år och månad i blad arbetsbeskrivning
Application.Goto Sheets("CDPPT").Range("G2")
Range("G2").Copy
Sheets("Arbetsbeskrivning").Select
Range("C10").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("D10").Activate
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=RIGHT(RC[-1],2)"
Range("D10").Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("D10").Select
Selection.TextToColumns Destination:=Range("D10"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Range("D9").Activate
ActiveCell.FormulaR1C1 = "=VLOOKUP(R[1]C,Datalistor!R[-6]C[1]:R[5]C[2],2,0)"
Range("C9").Activate
ActiveCell.FormulaR1C1 = "=Left(R[1]C,4)"
Range("C4").Activate
' kopierar data och skapar Pivotdata Telia försäljning
Sheets("CDPPT").Select
Range(Range("A2"), Range("A2").End(xlToRight).End(xlDown)).Copy
Destination:=Sheets("Matchning"). _
Range("A2")
Application.CutCopyMode = False
Sheets("CDPPT").Select
Range(Range("A2"), Range("A2").End(xlToRight).End(xlDown)).Copy
Destination:=Sheets("Pivotgrund"). _
Range("A2")
Application.CutCopyMode = False
ActiveWorkbook.RefreshAll
' Tar bort dubletter
Application.Goto Sheets("Matchning").Range("A:M")
Selection.Sort Key1:=Range("F1"), Order1:=xlDescending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Application.Goto Sheets("Matchning").Range("A1")
Range(Range("A1"), Range("A1").End(xlToRight).End(xlDown)).Select
ActiveSheet.Range("A:L").RemoveDuplicates Columns:=6, Header:= _
xlYes
ActiveWorkbook.RefreshAll
' letar in Pivotdata
Application.Goto Sheets("Matchning").Range("H2")
ActiveCell.FormulaR1C1 = "=VLOOKUP(C[-2],Pivot!C[-7]:C[-6],2,0)"
Range("H2").Select
Selection.Copy
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
ActiveWorkbook.RefreshAll
' Skapar fil med prod med saknad data
Application.Goto Sheets("Matchning").Range("A1")
Range("A1").Select
ActiveSheet.Range("$A:P").AutoFilter Field:=12, Criteria1:= _
"Check for data"
Range(Range("A1"), Range("A1").End(xlToRight).End(xlDown)).Copy
Range("A1").Select
Workbooks.Add
ActiveSheet.Paste
ActiveWorkbook.Windows(1).Caption = "Produktdata saknas"
Columns("M:P").Select
Selection.Delete Shift:=xlToLeft
Range("A1").Select
Windows("Datamatchningsfil.xlsm").Activate
Application.Goto Sheets("Matchning").Range("A1")
ActiveSheet.ShowAllData
ActiveWorkbook.RefreshAll
Application.ScreenUpdating = True
Sheets("Arbetsbeskrivning").Select
Range("C13").Select
With Selection.Font
.Color = -16776961
.TintAndShade = 0
End With
Selection.Font.Bold = True
ActiveCell.FormulaR1C1 = _
"Steg 1 klart!"
Range("C14").Select
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
MsgBox ("Steg 1 klart")
End Sub

Related

How do i combine macro module with the rest of the code

I'm a beginner, so any help is much appreciated, I want to combine this macro with the first code, but I don't know how to do that or where to put it.
this is the first code (it has a mistake in it, but I already have an answer on how to fix it, so it's alright):
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("inbd")
Dim wsDestination As Worksheet: Set wsDestination = Sheets("test")
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Range("A1:N" & LastRow).AutoFilter Field:=1, Criteria1:=Worksheets("test").Cells(1, 26).Value
ws.Range("f2:f" & LastRow).SpecialCells(xlCellTypeVisible).Copy Range("C6")
DestinationRow = wsDestination.Cells(wsDestination.Rows.Count, "C").End(xlUp).Row + 1
wsDestination.Range("C" & DestinationRow).PasteSpecial xlPasteValues
Application.CutCopyMode = False
ws.Range("A1:N" & LastRow).AutoFilter Field:=1
End Sub
currently the first code filters and copies table data in the parameter that I want into another worksheet, but I need a more complex version of the copy so I recorded it in macro, which is super long and looks like this:
Sub Macro8()
'
' Macro8 Macro
'
'
Sheets("INBD").Select
Range("Table1[Description]").Select
Selection.Copy
Sheets("Sheet1").Select
Range("Table19[Description]").Select
ActiveSheet.Paste
Range("D18").Select
Sheets("INBD").Select
Range("Table1[Invoice Date]").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("Table19[Invoice '#]").Select
ActiveSheet.Paste
Sheets("INBD").Select
Range("Table1[Invoice '#]").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("Table19[Invoice '#]").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Sheets("INBD").Select
Range("Table1[HS Code]").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("Table19[HS Code]").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Sheets("INBD").Select
Range("Table1[Unit]").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("Table19[M. Unit]").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Range("Table19[Description]").Select
Application.CutCopyMode = False
Selection.Copy
Range("E13").Select
ActiveSheet.Paste
Sheets("INBD").Select
Range("Table1[QTY]").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("Table19[QTY]").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Sheets("INBD").Select
Range("Table1[Unit Price]").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("Table19[Unit Price]").Select
ActiveSheet.Paste
Sheets("INBD").Select
Range("Table1[Curr.]").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("Table19[Curr]").Select
ActiveSheet.Paste
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Rows("13:22").Select
Rows("13:22").EntireRow.AutoFit
Selection.RowHeight = 30
Application.CutCopyMode = False
With Selection
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
What this does is that it copies values into a table, into specific columns, below the table I wrote in a bunch of stuff and made the color of the font white, so that when it copies, the table moves the cells down hence not altering anything below the table and leaves some space in between. After this I'm going to record a macro which deletes all rows in the table and any other data in the table to clear the document for a new entry.
One solution to combine two Macros would be just to type everything from the second Macro between the first and last line and paste in where you need its execution in the first code.
The other solution would be to "Call" the second Macro from the first Code by simply typing
Call Macro8
In your example :
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("inbd")
Dim wsDestination As Worksheet: Set wsDestination = Sheets("test")
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Range("A1:N" & LastRow).AutoFilter Field:=1, Criteria1:=Worksheets("test").Cells(1, 26).Value
ws.Range("f2:f" & LastRow).SpecialCells(xlCellTypeVisible).Copy Range("C6")
DestinationRow = wsDestination.Cells(wsDestination.Rows.Count, "C").End(xlUp).Row + 1
wsDestination.Range("C" & DestinationRow).PasteSpecial xlPasteValues
Application.CutCopyMode = False
ws.Range("A1:N" & LastRow).AutoFilter Field:=1
Call Macro8 ' Or Copy Paste the whole other code here
End Sub
I still strongly advise to follow the links from the comments of Foxfire And Burns And Burns about How to avoid using Select in Excel VBA.
Application.run ("macro8") <-is what I needed, I appreciate the advice though, I don't really have any knowledge in coding, but I will try to avoid using select if i can.

Macro copies from one workbook into another, Runs with no error but sometimes doesn't work

I am slowly learning VBA in Excel on my own so I'm sure this code can be picked a part. Basically users fill this area with info and click a button that in the background copies the data they populate, opens a new workbook and pastes it in the next open row. There are many users, and for some it works, for others it runs with no error but their info is not pasted in the new. location. Most of the stuff at the end is just reformatting, but I didn't want to take it out in case it could be a part of the problem.
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Sub FF_Temp_Upload()
'
' FF_Temp_Upload Macro
'
Application.ScreenUpdating = False
Dim Workbk As Workbook
Set Workbk = ThisWorkbook
Dim LR As Long
Dim Cell As Long
Dim Ret As String
LR = Range("B" & Rows.Count).End(xlUp).Row
Ret = IsWorkBookOpen("Location of the 2nd workbook/OVS Upload Template.xlsx")
If Ret = True Then
MsgBox "Template is currently being updated elsewhere. Please try again."
Exit Sub
Else
Workbooks.Open FileName:= _
"Location of the 2nd workbook/OVS Upload Template.xlsx"
End If
Workbk.Activate
Range("A2:C" & LR).Select
Selection.Copy
Windows("OVS Upload Template.xlsx").Activate
If Range("A2") = "" Then
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Else
Range("A1").Select
Selection.End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
End If
Workbk.Activate
Range("H2:H" & LR).Select
Application.CutCopyMode = False
Selection.Copy
Windows("OVS Upload Template.xlsx").Activate
If Range("L2") = "" Then
Range("L2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Else
Range("L2").Select
Selection.End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
End If
ActiveSheet.Range("$A$1:$M$100000").RemoveDuplicates Columns:=1, Header:=xlYes
LR = Range("B" & Rows.Count).End(xlUp).Row
Range("B2:B" & LR) = "=text(left(A2,8),""00000000"")"
Range("B2:B" & LR).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Range("C2:C" & LR) = "=""DCG""&MID(A2,9,4)"
Range("C2:C" & LR).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Range("D2:D" & LR).Select
Selection.Formula = "DT"
Range("I2:I" & LR).Select
Selection.Formula = "730"
Range("M2:M" & LR).Select
Selection.Formula = "MAJOH73"
ActiveWorkbook.Save
ActiveWindow.Close
Workbk.Activate
MsgBox "Articles Uploaded"
End Sub
You do not refer to Worksheets anywhere in your code. Thus, for some users, it works and for some it does not.
For those who works - their Excel file was saved with the correct Worksheet selected.
For those who does not work - their Excel file was saved with wrong Worksheet selected. Thus, when it is opened, the ActiveSheet is the wrong one and the code works there.
To fix it (quick and dirty) rewrite your code, refering the worksheet like this:
Worksheets("MyWorksheet").Range("$A$1:$M$100000").RemoveDuplicates Columns:=1
Then try to avoid Selection and ActiveSheet - How to avoid using Select in Excel VBA. At the end, each range or cell should be with refered Worksheet. Like this:
With Worksheets("MyName")
.Range("D2:D" & LR).Formula = "DT"
.Range("I2:I" & LR).Formula = "730"
.Range("M2:M" & LR).Formula = "MAJOH73"
End With

Stack Three Macros into One VBA Command

I have three macros (below) that work separately, but when I sandwich them together, only the first macro executes properly. I'm not getting an error; the other two macros just don't seem to run. Any advice on how to link them together so I can execute all at once?
Macro 1
Sub Update_Workbook()
Dim QryStr As String, cell As String
Dim a As Integer, b As Integer
Dim cellv As Variant
'Pause spreadsheet calculations until end of sub
Application.Calculation = xlManual
ActiveWorkbook.Sheets("Raw Data").Select
'Clear cells to import query
With Range("A1:O1").EntireColumn
.ClearContents
.NumberFormat = "General"
.Validation.Delete
End With
'Process SQL query string
QryStr = ActiveSheet.TextBox1.Value
Do While InStr(QryStr, "{&")
a = InStr(QryStr, "{&")
b = InStr(a, QryStr, "}")
cell = Mid(QryStr, a + 2, b - a - 2)
cellv = Range(cell).Value
If IsDate(cellv) Then
cellv = Format(cellv, "dd-mmm-yy")
End If
QryStr = Replace(QryStr, "{&" & cell & "}", cellv)
Loop
'Import data from query
With ActiveSheet.QueryTables.Add(Connection:="ODBC;DRIVER={Oracle in OraClient11g_home1};UID=xx;PWD=xx;SERVER=xx;DBQ=xx", _
Destination:=Range("A1"), Sql:=QryStr)
.MaintainConnection = False
.BackgroundQuery = False
.RefreshStyle = xlOverwriteCells
.Refresh
.Delete
End With
Finish_Sub:
Call ClearUnneededNames
Application.Calculation = xlCalculationAutomatic
End Sub
Sub ClearUnneededNames()
Dim savedNames As Integer
savedNames = 0
Do While ActiveSheet.Names.Count > savedNames
If InStr(ActiveSheet.Names(savedNames + 1).Name, "ExternalData") = 0 Then
savedNames = savedNames + 1
Else
ActiveSheet.Names(savedNames + 1).Delete
End If
Loop
End Sub
Macro 2
Sub Five_Felicia_for_MFG()
'
' Macro3 Macro
'
'
Range("A3:M3").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlUp)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWindow.SmallScroll Down:=-18
Range(Selection, Selection.End(xlUp)).Select
Range("A3:M1010").Select
Selection.Delete Shift:=xlUp
Sheets("5Felicia").Select
Range("A3:M34").Select
Selection.Copy
Sheets("5Felicia for MFG").Select
Range("A3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Sheets("5Felicia").Select
Range("A37:M37").Select
Range(Selection, Selection.End(xlDown)).Select
Range("A37:M692").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("5Felicia for MFG").Select
ActiveWindow.SmallScroll Down:=18
Range("A36").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveWindow.SmallScroll Down:=-48
Columns("A:M").Select
Application.CutCopyMode = False
ActiveSheet.Range("$A$1:$M$691").RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6, _
7, 8, 9, 10, 11, 12, 13), Header:=xlNo
End Sub
Macro 3
Sub DUMMY_ITEMS()
'
' DUMMY_ITEMS Macro
Dim LastRow As Long
Sheets("Operations").Range("H2:V73").Copy
With Sheets("Raw Data")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range("A" & LastRow + 1).PasteSpecial xlPasteValues
End With
End Sub
In VBA a Module can have several macros (or, more accurately, subroutines) in it.
But, when you call one of those macros, execution stops at the End Sub statement. Nothing else in the module will run regardless of how you "sandwich" them together within the module.
But subroutines can call other subroutines. So code like this will run all three of your macros:
Sub RunAllThree()
Update_Workbook
Five_Felicia_for_MFG
DUMMY_ITEMS
End Sub

Mass edit multiple workbooks of the same format

I'm very new to VBA (as of this morning), so excuse my ignorance. I have a few hundred Excel workbooks, all formatted exactly the same way (just with different text). I'm trying to both format and delete a few sheets within the workbooks (the same for alL).
I recorded a macro that works fine when applied individually, but I'm getting a runtime error when I try to run this as a means of mass format:
Sub LoopFiles()
Dim MyFileName, MyPath As String
Dim MyBook As Workbook
MyPath = "I:\Academic Networks\All scorecard copies, 6.18.2015"
MyFileName = Dir(MyPath & "*.xlsm")
Do Until MyFileName = ""
Workbooks.Open MyPath & MyFileName
Set MyBook = ActiveWorkbook
Application.Run "Workbook1.xlsm!ScorecardMacro"
MyBook.Save
MyBook.Close
MyFileName = Dir
Loop
End Sub
I keep getting a runtime error (9) - Subscript out of range. Any thoughts?
Here's the formatting/deleting I'm trying to apply to all my workbooks (which works fine when applied to one workbook at a time:
Sub ScorecardMacro()
'
' Scorecard Macro
'
'
Sheets.Add
Sheets("Scorecard").Select
Range("D3:D36").Select
Selection.Copy
Sheets("Sheet1").Select
Range("B1").Select
Selection.PasteSpecial Paste:=xlAll, Operation:=xlNone, SkipBlanks:=False _
, Transpose:=True
Sheets("Scorecard").Select
Range("A3:A36").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("B2").Select
Selection.PasteSpecial Paste:=xlAll, Operation:=xlNone, SkipBlanks:=False _
, Transpose:=True
Sheets("Scorecard").Select
Range("F3:I36").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("B3").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Sheets("Checklist").Select
Range("D4:D27").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
ActiveWindow.ScrollColumn = 28
Range("AJ1").Select
Selection.PasteSpecial Paste:=xlAll, Operation:=xlNone, SkipBlanks:=False _
, Transpose:=True
Sheets("Checklist").Select
Range("A4:A27").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("AJ2").Select
Selection.PasteSpecial Paste:=xlAll, Operation:=xlNone, SkipBlanks:=False _
, Transpose:=True
Sheets("Additional Information").Select
Range("A4:B14").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("BH1").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Sheets("Program Recommendations").Select
Range("A4:D21").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("BS1").Select
Selection.PasteSpecial Paste:=xlAll, Operation:=xlNone, SkipBlanks:=False _
, Transpose:=True
ActiveWindow.ScrollColumn = 1
Range("A2").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = ""
ActiveCell.FormulaR1C1 = _
"=MID(CELL(""filename""),SEARCH(""["",CELL(""filename""))+1,SEARCH(""]"",CELL(""filename""))-SEARCH(""["",CELL(""filename""))-1)"
Range("A2").Select
Selection.AutoFill Destination:=Range("A2:A6"), Type:=xlFillDefault
Range("A2:A6").Select
Sheets("Program Recommendations").Select
ActiveWindow.SelectedSheets.Delete
Sheets("Additional Information").Select
ActiveWindow.SelectedSheets.Delete
Sheets("Scorecard").Select
ActiveWindow.SelectedSheets.Delete
Sheets("Checklist").Select
ActiveWindow.SelectedSheets.Delete
End Sub
The error shows you are trying to access something that doesn't exist.
Since you are deleting something, its better to do all you updates first, then do all the deletes in the end.
If you do some deletes in between and then update, there might be some values/sheets missing
You are referring to a named range called "filename":
"=MID(CELL(""filename""),SEARCH(""["",CELL(""filename""))+1,SEARCH(""]"",CELL(""filename""))-SEARCH(""["",CELL(""filename""))-1)"
I suspect that name is not defined in the other workbooks.

Filter data in a column and then count

I have recorded a macro to make changes to a sheet. Basically it makes a few changes such as add a column move two columns over and so forth. The thing that I am confused with is adding a small code to give me a count of the total DL and IDL in the MO REAL column L separately and putting the total count on another sheet in the same workbook "Resultados" in cells B17 and C17... Any ideas on how this can be accomplished? Here is the recorded code:
Option Explicit
Sub DefineDL_IDL()
Dim wbTHMacro As Workbook, wsRegulares As Worksheet, wsRegularesDemitidos As Worksheet, wsTempActivos As Worksheet, _
wsTempJA As Worksheet, wsTempFit As Worksheet, wsTempDemitidos As Worksheet, wsPS As Worksheet, wsResultados As Worksheet, _
wsDLList As Worksheet, wssheet As Worksheet
Sheets("Regulares").Select
Columns("J:J").Select
Selection.Insert Shift:=xlToRight
Range("J1").Select
ActiveCell.FormulaR1C1 = "MO REAL"
Columns("K:K").Select
Selection.Cut
Columns("I:I").Select
Selection.Insert Shift:=xlToRight
Columns("Q:Q").Select
Selection.Cut
Columns("I:I").Select
Selection.Insert Shift:=xlToRight
Range("K1").Select
Selection.AutoFilter
ActiveSheet.Range("A:Z").AutoFilter Field:=11, Criteria1:= _
"INATIVE"
Rows("5:5").Select
Range("F5").Activate
Range(Selection, Selection.End(xlDown)).Select
Selection.Delete Shift:=xlUp
ActiveSheet.Range("A:Z").AutoFilter Field:=11
Range("L2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-3],'DL List'!RC[-11]:R[32]C[-10],2,0)"
Range("L2").Select
Selection.AutoFill Destination:=Range("L2:L5890")
Range("L2:L5890").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Range("L2").Select
ActiveSheet.Range("A:Z").AutoFilter Field:=11, Criteria1:="DL"
ActiveSheet.Range("A:Z").AutoFilter Field:=12, Criteria1:="#N/A"
Range("L23").Select
ActiveCell.FormulaR1C1 = "DL"
Range("L23").Select
Selection.Copy
Range("L25").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveSheet.Range("A:Z").AutoFilter Field:=12
Range("L4").Select
ActiveSheet.Range("A:Z").AutoFilter Field:=11, Criteria1:=Array( _
"G&A", "MOH", "IDL", "Other MOH"), Operator:=xlFilterValues
ActiveSheet.Range("A:Z").AutoFilter Field:=12, Criteria1:="#N/A"
Range("L7").Select
ActiveCell.FormulaR1C1 = "IDL"
Range("L7").Select
Selection.Copy
Range("L15").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
ActiveSheet.Paste
Application.CutCopyMode = False
Range("L7").Select
ActiveWorkbook.Worksheets("Regulares").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Regulares").AutoFilter.Sort.SortFields.Add Key:= _
Range("K1:K5890"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption _
:=xlSortNormal
ActiveSheet.Range("A:Z").AutoFilter Field:=12
Range("K2").Select
ActiveSheet.Range("A:Z").AutoFilter Field:=11
Range("G2").Select
ActiveCell.FormulaR1C1 = "1"
Range("G2").Select
Selection.Copy
Range("J2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, _
SkipBlanks:=False, Transpose:=False
Range("J2").Select
Application.CutCopyMode = False
End Sub
If you are counting the times "DL" and "IDL" occur...
'Count DL and IDL
count_DL = Application.WorksheetFunction.CountIf(ActiveSheet.Range("L:L"), "DL")
count_IDL = Application.WorksheetFunction.CountIf(ActiveSheet.Range("L:L"), "IDL")
'Paste results in Resultados sheet
Worksheets("Resultados").Range("B17") = count_DL
Worksheets("Resultados").Range("C17") = count_IDL
Your question is a little confusing without understanding a broader picture of what you're doing. All you need to do to get a count and put it in another sheet is:
Sheets("AnotherSheet").Range("B13") = Application.WorksheetFunction.CountA(Columns("G:G"))