Copy Range to new workbook - Not copying, error 9 - vba

I am receiving a Run-time error '9':
Subscript out of range.
The error occurs at the end.. I am trying to open a new spreadsheet, copy edited information into it, and then I will use a script following this to dump 8-12 more files based on selection INTO 'FName' ... which may or may not work.
This is highlighted when I click debug:
Workbooks("TFR7").Sheets("Sheet1").Range("A2:V" & LastRow).Copy Destination:=Workbooks(FName).Sheets("Sheet1").Range("A1")
I do not understand the error here? Is it my range selection to copy over?
Side note: I AM working to learn how to remove the instances of select, etc. FYI
Code is below:
Sub OpenReportThenEdit()
'This will open a designated report and edit it
'File pathway and name must be correct
'Any adjustments to file layout could 'break' macro
'First file will always be TFR7 and from there can go into more
'Currently only works for TFR7
Application.ScreenUpdating = False
Dim wb As Excel.Workbook
Dim LastRow As Long
Dim FName As String
'Open a report, delete header/footer rows
Set wb = Workbooks.Open("C:\Users\USER\Downloads\TFR7", False, False)
wb.Sheets(1).Rows("1:5").EntireRow.Delete
wb.Sheets(1).Range("A" & Rows.Count).End(xlUp).EntireRow.Delete
wb.Sheets(1).Range("A" & Rows.Count).End(xlUp).EntireRow.Delete
wb.Sheets(1).Range("J" & Rows.Count).End(xlUp).EntireRow.Delete
'Edit Sheet Font/Size
With Worksheets("Sheet1").Cells.Font
.Name = "Arial"
.Size = 9
End With
'Edit Sheet Alignment, etc.
With Worksheets("Sheet1").Cells
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.HorizontalAlignment = xlRight
.VerticalAlignment = xlBottom
.WrapText = False
End With
'Replace 'text to columns' and convert dates to Excel Date Value before
'Paste Values' to remove formula
Columns("L:O").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("L2").FormulaR1C1 = "=DATEVALUE(LEFT(RC[4],10))"
Range("L2").Copy Destination:=Range("L2:O2")
LastRow = Cells(Cells.Rows.Count, "A").End(xlUp).Row
Range("L2:O" & LastRow).FillDown
Range("P1:S1").Copy Destination:=Range("L1:O1")
Columns("L:O").Select
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "m/d/yyyy"
'Delete old date columns, remove duplicate values (by tracking numbers)
Columns("P:S").Select
Selection.Delete Shift:=xlToLeft
ActiveSheet.Range("A1:V" & LastRow).RemoveDuplicates Columns:=19, Header:= _
xlYes
'Select cells with values, turn them blue (because silly people want them blue)
LastRow = Cells(Cells.Rows.Count, "A").End(xlUp).Row
ActiveSheet.Range("A2:V" & LastRow).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
End With
'Open Workbook, set Workbook as Destination for
FName = "C:\Users\USER\Downloads\Daily_" & _
Format(Date, "mmdd") & ".xlsm"
Workbooks.Add.SaveAs Filename:=FName, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
Workbooks("TFR7").Sheets("Sheet1").Range("A2:V" & LastRow).Copy Destination:= _
Workbooks(FName).Sheets("Sheet1").Range("A1")
Application.ScreenUpdating = True
End Sub

Work with objects instead:
Dim otherWB As Excel.Workbook
'// other code here
Set otherWB = Workbooks.Add
otherWB.SaveAs Filename:=FName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
'// wb is already set to original workbook, otherWB is set to new workook
wb.Sheets("Sheet1").Range("A2:V" & LastRow).Copy Destination:=otherWB.Sheets("Sheet1").Range("A1")

Related

Copying result rows from filtered sheet ignoring blank or empty

everyone. I am newie on this, but i need this so i am asking for your help.
I am building a macro to copy filtered data from several books to a consolitation one. The following code run fine until one filtered worksheet has no result rows, then it copy a range of empty cells, in that moment a receive an error 1004 that a can't solve. This is my code (result of several adaptation of code to my need):
Sub MergeDataFromWorkbooks()
Dim wbk As Workbook
Dim wbk1 As Workbook
Set wbk1 = ThisWorkbook
Dim Filename As String
Dim Path As String
Path = "D:\Reportes\Prueba\"
Filename = Dir(Path & "*.xlsx")
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Do While Len(Filename) > 0
Set wbk = Workbooks.Open(Path & Filename)
wbk.Activate
If ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
With ActiveSheet
.AutoFilterMode = False
.Range("B6:BB6").AutoFilter field:=8, Criteria1:="*Nacional*"
End With
Range("B7").Select
Range(Selection, "BA7").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Windows("Merged.xlsm").Activate
Application.DisplayAlerts = False
Dim lr As Double
lr = wbk1.Sheets(1).Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
'Sheets("Hoja1").Cells(Rows.Count, 1).End(xlUp).Offset(1).PasteSpecial xlPasteValues
Sheets("Hoja1").Select
Cells(lr + 1, 1).Select
ActiveCell.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=True
Application.CutCopyMode = False
wbk.Close True
Filename = Dir
Loop
MsgBox "All the files are copied and pasted in Merged."
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
you have to check whether there are any filtered cells, so wrap copy/paste statements inside some If - Then as follows:
With ActiveSheet
.AutoFilterMode = False
.Range("B6:BB6").AutoFilter field:=8, Criteria1:="*Nacional*"
End With
If Application.WorksheetFunction.Subtotal(103, Intersect(ActiveSheet.UsedRange, Columns(2))) > 1 Then
Range("B7").Select
Range(Selection, "BA7").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.copy
Windows("Merged.xlsm").Activate
Application.DisplayAlerts = False
Dim lr As Double
lr = wbk1.Sheets(1).Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).row
'Sheets("Hoja1").Cells(Rows.Count, 1).End(xlUp).Offset(1).PasteSpecial xlPasteValues
Sheets("Hoja1").Select
Cells(lr + 1, 1).Select
ActiveCell.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=True
Application.CutCopyMode = False
End If
wbk.Close True
Filename = Dir
Check for visible values in the filtered range before copying.
With ActiveSheet
.AutoFilterMode = False
with .Range("B6:BB6")
.AutoFilter field:=8, Criteria1:="*Nacional*"
with .resize(.rows.count-1, .columns.count).offset(1, 0)
if cbool(application.subtotal(103, .cells)) then
.SpecialCells(xlCellTypeVisible).copy
end if
end with
end with
End With
It's probably better to work out the destination beforehand and use the Destination parameter of the copy operation.

Issue in Vba code in copying and Union ranges based on particular condition

My code is giving me runtime error 424 in the highlighted line. What could be the possible reason? My rows are not getting copied. CopyRng12 creates some sort of issue.
sub grouping()
Set ws6 = Workbooks("A.xlsx").Worksheets("X1")
Set ws7 = Workbooks("B.xlsx").Worksheets("X2")
LastRowu = ws6.Cells(Rows.Count, "B").End(xlUp).Row
LastRowb = ws7.Cells(Rows.Count, "K").End(xlUp).Row
LastRowb1 = ws7.Cells(Rows.Count, "L").End(xlUp).Row
Application.Calculation = xlAutomatic
ws6.Columns("E:E").Insert Shift:=xlToRight,
CopyOrigin:=xlFormatFromLeftOrAbove
ws6.Range("E2").FormulaR1C1 = _
"=VLOOKUP(RC[-1],'[B.xlsx]X2'!C11:C12,2,0)"
ws6.Range("E2").AutoFill Destination:=ws6.Range("E2:E" & LastRowu),
Type:=xlFillDefault
With ws6.UsedRange
.Copy
.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End With
ws6.Cells.Replace "#N/A", "Company Code Not Found", xlWhole
Workbooks("A.xlsx").Worksheets("X1").Activate
ws6.Columns("D:D").Select
Selection.Copy
ws6.Columns("A:A").Select
Selection.Insert Shift:=xlToRight
For q = LastRowu - 1 To 1 Step -1
If ws6.Cells(q, "F").Value = "G1" Then
**If Not CopyRng12 Is Nothing Then
Set CopyRng12 = Application.Union(CopyRng12, ws6.Rows(q))**
Else
Set CopyRng12 = ws6.Rows(q)
End If
End If
Next q
Set wbmm = Workbooks("G1.xlsx")
Workbooks("G1.xlsx").Activate
Dim wsmm As Worksheet
Set wsmm = wbmm.Worksheets("X1")
Workbooks("G1.xlsx").Worksheets("X1").Activate
CopyRng12.Copy
Worksheets("X2").ClearContents
ActiveSheet.Paste
End Sub

Excel VBA Loop Through Column and Save Result

This is a little challenging to me
I have the following code which works just like I wanted. But I need the code to loop through Sheet1 Column A and copy and paste the value to Sheet2(R1) Then loop through Sheet1 column B and copy each value paste it to Sheet2(I7) then save the worksheet as a new PDF document
See Picture for example excel sheet
example
Sub Macro2()
'
' Macro2 Macro
'
'
Sheets("Sheet1").Select
Range("A2").Select
Selection.Copy
Sheets("Sheet2").Select
Range("R1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
With Selection.Font
.Name = "Calibri"
.Size = 20
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
Sheets("Sheet1").Select
Range("B2").Select
Selection.Copy
Sheets("Sheet2").Select
Range("I7").Select
ActiveSheet.Paste
Application.CutCopyMode = False
With Selection.Font
.Name = "Calibri"
.Size = 16
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
Dim i As Integer
For i = 1 To 2
Next i
ThisWorkbook.Sheets("Sheet2").Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\" & CStr(i) & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=True, _
OpenAfterPublish:=False
End With
End Sub
You can use the following codes to loop through rows and/or columns if you add the function below at the end (below your actual sub) of the same "Module" your sub is located in.
sub yourcode
ThisWorkbook.Worksheets("worksheetX").range(col_letter(column_number) & rownumber).Value
end sub
Function col_letter(lngCol As Long) As String 'Sub nr_to_letter()
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
col_letter = vArr(0)
End Function
And it will automatically convert the column_number to the column letter in the .range("..
And the following generalized code detects the last row of your column:
'Find the last used row in a Column: column B in this example
Dim LastRow As Long
sheets(name(Sheet)).Select
sheets(name(Sheet)).Activate
'MsgBox (Sheet)
With ActiveSheet
LastRow = .Cells(.Rows.count, "B").End(xlUp).Row
End With
I learned a lot of the basics by looking up standard solutions to basic problems I stumbled upon from:
Source: http://www.rondebruin.nl/
And I think this code could perform your desired task:
Sub Macro2()
'
' Macro2 Macro
'
'
Sheets("Sheet1").Select
Range("A2").Select
'detect last row in column A sheet1:
Dim LastRow As Long
Sheets("Sheet1").Select
Sheets("Sheet1").Activate
'MsgBox (Sheet)
With ActiveSheet
LastRow_A = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
MsgBox (LastRow_A)
'here the function to convert column number to column letter is used:
'Range(col_letter(1) & "2:A" & LastRow).Select
MsgBox ("As you can see the function converts the index of the col_letter to a alphabetic letter: " & col_letter(1))
For loop_through_column_A = 2 To LastRow_A
Range(col_letter(1) & loop_through_column_A).Select
Selection.Copy
Sheets("Sheet2").Select
Range("R" & loop_through_column_A - 1).Select 'ensure it starts pasting at row 1
ActiveSheet.Paste
Application.CutCopyMode = False
With Selection.Font
.Name = "Calibri"
.Size = 20
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
Next loop_through_column_A
Sheets("Sheet1").Select
Range("B2").Select
'detect last row in column B sheet1:
Dim LastRow_B As Long
Sheets("Sheet1").Select
Sheets("Sheet1").Activate
'MsgBox (Sheet)
With ActiveSheet
LastRow_B = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
MsgBox (LastRow_B)
'loop through column Sheet1
For loop_through_column_B = 2 To LastRow_B
Range("B" & loop_through_column_B).Select
Selection.Copy
Sheets("Sheet2").Select
Range("I" & 5 + loop_through_column_B).Select
ActiveSheet.Paste
Application.CutCopyMode = False
With Selection.Font
.Name = "Calibri"
.Size = 16
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
'To save the pdf every iteration (after you have already completely iterated through column A in the first for-loop:
'"Insert here."
Next loop_through_column_B
'include this in the loop if you want to save the pdf every time you add a different pasted row where it says: "Insert here."
ThisWorkbook.Sheets("Sheet2").Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\" & CStr(i) & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=True, _
OpenAfterPublish:=False
End Sub
'Here the following function IS used:
Function col_letter(lngCol As Long) As String 'Sub nr_to_letter()
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
col_letter = vArr(0)
End Function

How to copy formula from a selected range and copy it to the next empty row with macros

I will be adding data into my workbook everyday and I will normally use a set of formulas to calculate rate of failures and success for me. I already have the code for compiling the data but what I lack now is how to copy the set of formulas for the next empty cell so that it can help me calculate the rates. My set of formula is added from "P22" to "AB22", and I need to copy those formulas to next empty row. This is the macros i have now, if kind enough do check and see if there are places for improvement as i'm still new to vba. Thank you very much.
Sub trial()
Dim wb As Workbook, wb2 As Workbook, wb3 As Workbook
Dim ws As Worksheet
Dim fn As String
Set wb = ActiveWorkbook
Set ws = Sheets.Add(After:=Sheets(Worksheets.Count))
Dim Ret
Ret = Application.GetOpenFilename("Lkl Files (*.lkl), *.lkl")
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$A$1"))
.Name = "SPC_PLTB_450B_12092107_25°C_CW"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 65001
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileDecimalSeparator = ","
.TextFileThousandsSeparator = "."
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End If
Sheets(2).Activate
'this is for the date (loop)
Dim FirstCell As String
Dim i As Integer
FirstCell = "C19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
ActiveCell = Format(Date, "mm/dd/yyyy")
ws.Activate
ws.AutoFilterMode = False
ws.Range("$A$9:$P$417").AutoFilter Field:=5, Criteria1:= _
"1"
Range("F31:F401").Select
Selection.Copy
Sheets(2).Activate
'this is for the raw data
FirstCell = "D19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Sheets(3).Activate
FirstCell = "C19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
ActiveCell = Format(Date, "mm/dd/yyyy")
ws.Activate
Range("D31:D401").Select
Application.CutCopyMode = False
Selection.Copy
Sheets(3).Activate
FirstCell = "D19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Sheets(4).Activate
FirstCell = "C19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
ActiveCell = Format(Date, "mm/dd/yyyy")
ws.Activate
Range("G31:G401").Select
Application.CutCopyMode = False
Selection.Copy
Sheets(4).Activate
FirstCell = "D19"
Range(FirstCell).Select
Do Until ActiveCell.Value = ""
If ActiveCell.Value = "" Then
Exit Do
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
End Sub
Example of my worksheet
It's tricky to give an ideal solution without knowing more about your existing Excel file, but I made some assumptions based on what you posted and put together an Excel file with a couple possible solutions for you.
Since we can't attach files to posts here I uploaded it to free file host FileTown; you can download the [macro-disabled] XLSX file here.
Follow the steps starting on sheet 'Example1' for an example of what I meant about creating formulas now for the data you will add later, as well as how to make charts auto-update by making your data into an Excel 'table', and how to create a Data Connection to your source data file so you don't need to re-import it any time the data changes, all without macros.
Not to deter you from learning about VBA & macro's but Excel has some very powerful built-in data management features which, in this case, might be a better approach than a custom one.
On the other hand, I first starting learning VBA (in the 90's with Excel v.5) by recording macros while doing simple repetitive tasks, and then experimenting with the generated VBA by "changing this line or deleting that one" and seeing what happened; about half of the code Excel auto-generates in a recorded macro is probably extraneous. (Just make a backup copy of your files before messing with them, and check MSDN/VBA or Google for anything you're curious about, and there's nothing to lose... I'm a big fan of Excel because, between VBA and its' built-in functions, its' capabilities are endless!)
Not to sway you from learning VBA, but I think you can get away without it in this case.
You could make a small change to the formulas in "P22" to "AB22" so that they stay blank if there is no data in "D to N".
Using your example, copy cell P22 and paste into cell P23. Next, put an "if" statement around your formula, like:
=IF ( D23 = "" , "" , {your existing formula here} )
...and "fill" that formula to the right, and down a few dozen rows. Cells "P to AB" will be blank until you enter data on the left side of your worksheet. It's tough to explain but if this doesn't make sense I can send you a sample worksheet. I

Macro That Shows Dialog Box Upon Close If Certain Condition Occurs For Multiple Excel Files in a Folder

The following code loops through a bunch of .xlsx files in a folder and performs certain tasks such as insterting data validation in a specific cell range, conditional formatting within the same range and protecting the sheet and entire workbook to protect the integrity of the data. I would like to add one more piece of logic to the code below. I would like to add code to have a dialiog box pop up informing a user of a missed responses in the data validation range. So in simple terms, if person is required to enter a response (Y or N) in a cell for a given amount of rows misses one, a dialog box will pop up when he or she closes the Excel to let them know. I don't wan't to restrict the person from saving file. Just to let them know that a response was missed. Thank you!
Sub ProtectSheetsAndDataValidation()
'
' Access_Review_Final Macro
'
Dim MyFolder As String
Dim myFile As String
Dim wbk As Workbook
On Error Resume Next
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
myFile = Dir(MyFolder) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
Do While myFile <> “”
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(FileName:=MyFolder & myFile)
'Replace the line below with the statements you would want your macro to perform
If Err.Number <> 0 Then
MsgBox ("Unable to open file " & myFile)
End If
On Error GoTo 0
Sheets(1).Select
Sheets(1).Name = "MAR"
Cells.Select
Range("K1").Activate
With Selection
.HorizontalAlignment = xlGeneral
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection
.HorizontalAlignment = xlGeneral
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
LastRow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row
Range("A1").Select
Selection.Cut
Range("J1").Select
ActiveSheet.Paste
Range("K4:K" & LastRow).Select
Selection.Locked = False
Selection.FormulaHidden = False
Range("K4:K" & LastRow).Select
With Selection
.HorizontalAlignment = xlCenter
End With
Range("K4:K" & LastRow).Select
With Selection.Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Range("K4:K" & LastRow).Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=LEN(TRIM(K4))>0"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.Pattern = xlNone
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("J3").Select
Selection.Copy
Range("K3").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Range("K4").Select
Range("K4:K" & LastRow).Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="Y,N,n,y"
.IgnoreBlank = False
.InCellDropdown = False
.InputTitle = ""
.ErrorTitle = "Invalid Response"
.InputMessage = "Please Enter ""Y"" or ""N"". Case doesn't matter."
.ErrorMessage = "Please Enter ""Y"" or ""N"". Case doesn't matter."
.ShowInput = True
.ShowError = True
End With
Range("K11").Select
Range("K16").Select
Rows("3:3").Select
Range("H3").Activate
Selection.AutoFilter
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
, AllowFormattingColumns:=True, AllowFormattingRows:=True, AllowSorting:= _
True, AllowFiltering:=True, Password:="adgiam"
ActiveWorkbook.Protect Structure:=True, Windows:=False, Password:="adgiam"
ActiveWindow.ScrollColumn = 9
wbk.Close SaveChanges:=True
myFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = True
MsgBox "Macro has completed! Woot! Woot!"
End Sub
you could use Workbook_BeforeClose event handler
what follows assumes that:
worksheet "Validation" is to be checked for missing validation
in worksheet "Validation", validation cells are in column K from row 4 down to last not empty row of column "B"
here's the code
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim cell As Range
Dim addrStrng As String
With Worksheets("Validations")
For Each cell In .Range("K4:K" & .Cells(.Rows.Count, "B").End(xlUp).Row)
With cell.Validation
.IgnoreBlank = False
If Not .Value Then addrStrng = addrStrng & cell.address(False, False) & vbCrLf
End With
Next cell
If addrStrng <> "" Then
MsgBox "There are validation data input missing in: " & vbCrLf & vbCrLf & addrStrng
Cancel = True
End If
End With
End Sub