Runtime error when trying to format cells in a range - vba

I am having a lot of trouble with my vba code. I have created a sub that will execute when the file is opened. However, I keep getting a runtime error that says I have an application defined or object-defined problem. This code works when the "With Cells(13, dateFinder.Column)" block is not accompanied by the "With Cells(17, dateFinder.Column)" block below it.
Here is the code:
Sub equityRaiseOpen()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set ws1 = Worksheets("PRESENTATION")
Set ws2 = Worksheets(7)
ws2.Activate
Dim dateRange As Range
ws2.Unprotect
Dim dte As Date
'this block finds current quarter ending date
If Application.WorksheetFunction.RoundUp(Month(Now()) / 3, 0) = 1 Then
dte = DateValue("3/31/" & Year(Now()))
ElseIf Application.WorksheetFunction.RoundUp(Month(Now()) / 3, 0) = 2 Then
dte = DateValue("6/30/" & Year(Now()))
ElseIf Application.WorksheetFunction.RoundUp(Month(Now()) / 3, 0) = 3 Then
dte = DateValue("9/30/" & Year(Now()))
ElseIf Application.WorksheetFunction.RoundUp(Month(Now()) / 3, 0) = 4 Then
dte = DateValue("12/31/" & Year(Now()))
End If
Set dateRange = Range("FFO___AFFO_SUMMARY")
Dim iterator As Range
Dim colNum As Integer
'this block finds the column number for the current quarter ending date
For Each iterator In dateRange
If iterator = dte Then
colNum = iterator.Column
End If
Next
ws2.Range("B1") = dte
Dim dateFinder As Range
Set dateFinder = ws2.Range("B1")
Dim i As Integer
'Call putDates
i = 9
'ws2.Unprotect
Dim j As Integer
Set dateFinder = ws2.Range("B1")
For j = 1 To i
Cells(12, dateFinder.Column) = 0.4
'create data validiation for debt source
Debug.Print Cells(13, dateFinder.Column).Address
With Cells(13, dateFinder.Column)
.Interior.Color = RGB(255, 255, 255)
.Locked = False
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
With .Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=DebtList"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
.Value = "Revolver"
End With
With Cells(17, dateFinder.Column)
.Interior.Color = RGB(255, 255, 255)
.Locked = False
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
With .Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="ATM,Common, Preferred"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
.Value = "ATM"
End With
Set dateFinder = dateFinder.Offset(0, 2)
Next j
'ws2.Protect
End Sub

Related

Hyperlink with spaces

I have a worksheets for my projects.
the first sheet is the main one the containing all the name of the projects.
the author sheets are for every project.
in the main sheet the name of the project has hyperlink to his sheet.
when running the code I got a pop msgbox that I write the new project name (look for "project_name").
the code does stuff.
but near the end there is the hyperlink code. (look for ActiveSheet.Hyperlinks.Add....)
so my problem is:
when I choose a project name like "abcd" everything works ok. But when I choose name like "ab cd". the code runs but the hyperlink doesn't work.
I realized that having a space in the project name makes the code not work.
thanks for the help.
p.s.
The notes are in Hebrew.
Sub New_project()
'--------------------------------------------------------------------------------------------------תחילת ריצת קוד
Dim Start, Finish, TotalTime As Date
Start = Timer
'--------------------------------------------------------------------------------------------------ביטול חישובים ועדכוני מסך והתראות
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
'--------------------------------------------------------------------------------------------------החזרת חישובים ועדכוני מסך והתראות
'Application.Calculation = xlCalculationAutomatic
'Application.ScreenUpdating = True
'Application.DisplayAlerts = True
'Application.AskToUpdateLinks = True
'--------------------------------------------------------------------------------------------------פתיחת חלונית והקלדת שם הפרויקט
'--------------------------------------------------------------------------------------------------אם לחצו cancel אז יציאה מהקוד
Dim project_name As String
project_name = InputBox("נא להקליד את שם הפרויקט החדש")
If Len(project_name) < 1 Then
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
MsgBox ("יציאה מהקוד")
Exit Sub
End If
'--------------------------------------------------------------------------------------------------בדיקה האם שם הגיליון לפרויקט החדש כבר קיים
Dim curSheet As Worksheet
Dim ArraySheets() As String
Dim x As Variant
Dim sheet_existing As Integer
x = 0
sheet_existing = 0
For Each curSheet In ActiveWorkbook.Worksheets
If curSheet.Name Like project_name Then
Worksheets(project_name).Activate
sheet_existing = 1
Finish = Timer
TotalTime = Format((Finish - Start) / 86400, "hh:mm:ss")
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
MsgBox ("שם הפרויקט כבר קיים" & vbNewLine & "זמן ריצת קוד: " & TotalTime)
Exit Sub
End If
Next curSheet
'iComp = StrComp(str1, str2, vbBinaryCompare)
'--------------------------------------------------------------------------------------------------הוספת גיליון חדש בסוף הקובץ
If sheet_existing = 0 Then
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = project_name
End If
'--------------------------------------------------------------------------------------------------הוספת כותרות
Range("A1") = "#"
Range("B1") = "תאריך"
Range("C1") = "שלב"
Range("D1") = "איש קשר"
Range("E1") = "הערות"
Range("F1") = "מסמכים"
Range("G1") = "ימים"
Range("H1") = "צבירה"
'--------------------------------------------------------------------------------------------------רוחב עמודה
Columns("A").ColumnWidth = 9
Columns("B").ColumnWidth = 11
Columns("C").ColumnWidth = 30
Columns("D").ColumnWidth = 16
Columns("E").ColumnWidth = 17
Columns("F").ColumnWidth = 9
Columns("G").ColumnWidth = 6
Columns("H").ColumnWidth = 10
'--------------------------------------------------------------------------------------------------הוספת מסגרת לתאים
Dim rng1 As Range
Set rng1 = Range(Cells(1, 1), Cells(27, 8))
With rng1.Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
Range("A:H").HorizontalAlignment = xlCenter
Range("A:H").VerticalAlignment = xlCenter
Rows(1).Font.Bold = True
Columns(1).Font.Bold = True
Range("A1:H1").Interior.Color = RGB(0, 176, 240)
Range("A2") = 1
Range("B2") = Date
'Range("C2") = "רשום כאן את השלב הראשון"
Range("G2") = 0
Range("H2") = 0
Range("N1:Q1").Merge
Range("N2:Q12").Merge
Range("N1:Q1").Interior.Color = RGB(0, 176, 240)
Range("N1:Q1") = "הערות"
'--------------------------------------------------------------------------------------------------הוספת מסגרת לתאים
Dim rng2 As Range
Set rng2 = Range(Cells(1, 14), Cells(12, 17))
With rng2.Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
Range("N:Q").HorizontalAlignment = xlCenter
Range("N:Q").VerticalAlignment = xlCenter
'--------------------------------------------------------------------------------------------------ספירת גיליונות בקובץ
Dim SheetCountA As Integer
SheetCountA = Application.Sheets.Count
'--------------------------------------------------------------------------------------------------העתקת כפתור חזרה לגיליון החדש
Sheets(SheetCountA - 1).Select
ActiveSheet.Shapes.Range(Array("Rectangle 1")).Select
Selection.Copy
Sheets(SheetCountA).Select
ActiveSheet.Paste Destination:=Worksheets(SheetCountA).Range("K1")
Sheets(SheetCountA - 1).Select
Range("B1").Copy
Sheets(SheetCountA).Select
Range("B1").PasteSpecial Paste:=xlPasteFormats
Application.CutCopyMode = False
Range("A1").Select
Sheets(SheetCountA - 1).Select
Range("A1").Select
Sheets("סיכום").Select
Dim LastRowA As Integer
LastRowA = Application.CountA(Range("B:B"))
'--------------------------------------------------------------------------------------------------הוספת מספור לפרויקט החדש
Cells(LastRowA + 1, 1) = Cells(LastRowA, 1) + 1
'--------------------------------------------------------------------------------------------------הוספת היפר-לינק
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:= _
project_name & "!A1", TextToDisplay:=project_name
Cells(LastRowA + 1, 2).HorizontalAlignment = xlCenter
Cells(LastRowA + 1, 2).VerticalAlignment = xlCenter
Range("A1").Select
'--------------------------------------------------------------------------------------------------זמן סיום ריצת קוד וחישוב
Finish = Timer
TotalTime = Format((Finish - Start) / 86400, "hh:mm:ss")
MsgBox ("הדו''ח מוכן" & vbNewLine & "זמן ריצת קוד: " & TotalTime)
'--------------------------------------------------------------------------------------------------שאלה האם לעבור לקוד שמרענן את הקובץ
Dim answer2 As Integer
answer2 = MsgBox("?האם לרענן את הקובץ", vbYesNo + vbQuestion, "מעבר לקוד הבא")
If answer2 = vbYes Then
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Call Refresh_file
End If
'--------------------------------------------------------------------------------------------------שמירת הקובץ
ThisWorkbook.Save
'--------------------------------------------------------------------------------------------------החזרת חישובים ועדכוני מסך והתראות
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
End Sub
To make the hyperlink valid, you just need to wrap the sheet name in quotes, so:
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:= _
project_name & "!A1", TextToDisplay:=project_name
becomes
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:="'" & _
project_name & "'" & "!A1", TextToDisplay:=project_name

Excel VBA - Save changes to "Book16" error

I have some data in my excel file and based on that data I'm using a macro for generating the report which should be saved in the place specified by path provided by the user. On my laptop, with Win10 everything is working fine, but on PC there is an error when we try to generate a report. Instead of saving the report in provided place excel is asking me to save data in "Book16" as shows the screenshot below. Do I have no idea why?
Here is the code of macro responsible for creating the report:
Sub Nationalreports()
Dim sh1 As Worksheet, N As Long
Dim st As String
Dim wbUnSaved As Workbook
Dim wbSaved As Workbook
Dim RedemptiontypeIncHdgs As Range
Dim RedemptiontypeExcHdgs As Range
Dim Fr As Long, LR As Long
Dim vaFiles As Variant
Dim i As Long
Dim wbkToCopy As Workbook
Dim ws As Worksheet, strFile As String
Dim File_path As String
Dim qry As QueryTable
Dim FilNams As Variant
Dim FilNamCntr As Long
Dim strQryName As String
Dim lastrow As Long
Application.ScreenUpdating = False
If Range("E8").Value = 0 Then
MsgBox "Please Specify FilePath", vbExclamation, "Please Specify
FilePath"
Range("E8").Activate
Exit Sub
End If
File_path = Sheets("Control").Range("E8").Value
Set wbksaved = ActiveWorkbook
MsgBox "Please Select MVRT Reports", vbInformation, "Select Files"
FilNams = Application.GetOpenFilename(FileFilter:="CSV Files
(*.csv),*.csv", _
Title:="Select Textfile to
Import", _
MultiSelect:=True)
If TypeName(FilNams) = "Boolean" Then
MsgBox "No Files Selected", vbExclamation, "No Files Selected"
Exit Sub
Else
End If
For FilNamCntr = LBound(FilNams) To UBound(FilNams)
FilNams(FilNamCntr) = "TEXT;" & FilNams(FilNamCntr)
Next FilNamCntr
For FilNamCntr = LBound(FilNams) To UBound(FilNams)
Sheets("Data").Cells.NumberFormat = "#"
Set wbkToCopy = Workbooks.Add
With ActiveSheet
If .Range("A" & Rows.Count).End(xlUp).Row = 1 Then
lastrow = 1
Else
lastrow = .Range("A" & Rows.Count).End(xlUp).Row + 1
End If
Set qry = .QueryTables.Add(Connection:=FilNams(FilNamCntr), _
Destination:=.Range("A" & lastrow))
With qry
.Name = "Filename"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End With
'-------------------------------------------------------------------------------------------
'NEW CODE:
'-------------------------------------------------------------------------------------------
'progress
'Rows("1:1").Delete
'ActiveSheet.UsedRange.Columns("A:T").SpecialCells(xlCellTypeVisible).Copy
'wbksaved.Sheets("Data").Cells(Rows.Count, "A").End(xlUp).Offset(0).PasteSpecial Paste:=xlPasteValues
ActiveSheet.UsedRange.Columns("A:T").SpecialCells(xlCellTypeVisible).Select
Selection.Copy
'wbksaved.Sheets("Data").Activate
'Range("A1").Select
'ActiveSheet.Paste
wbksaved.Sheets("Data").Paste
'ERROR IS HERE ^^^^^^^^^^^^^
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
Application.DisplayAlerts = False
ActiveWorkbook.Close False
Application.DisplayAlerts = True
Next FilNamCntr
Set wbkToCopy = Workbooks.Add
wbkToCopy.Sheets(1).Name = "Duplicates,Invalid"
wbkToCopy.Worksheets.Add().Name = "Breakdown"
wbkToCopy.Worksheets.Add().Name = "Summary"
wbksaved.Sheets("Redemption").UsedRange.Columns("C:D").Copy
Sheets("Duplicates,Invalid").Range("A1").PasteSpecial Paste:=xlPasteValues
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
' Duplicates & Invalids Sheet
Sheets("Duplicates,Invalid").Activate
Columns("B").Cut Destination:=Columns("F")
Columns("A").Cut Destination:=Columns("B")
Range("B1").Value = "Duplicate Codes"
Range("F1").Value = "Invalid Codes"
Range("A2").Value = "1"
Range("A3").Value = "2"
On Error Resume Next
Cells(2, 1).AutoFill Destination:=Range("A2:A" & Range("B" & Rows.Count).End(xlUp).Row), Type:=xlFillSeries
Range("E2").Value = "1"
Range("E3").Value = "2"
On Error Resume Next
Cells(2, 5).AutoFill Destination:=Range("E2:E" & Range("F" & Rows.Count).End(xlUp).Row), Type:=xlFillSeries
Range("A1").Value = "Nr."
Range("E1").Value = "Nr."
Columns("A:F").EntireColumn.AutoFit
Columns("A:F").HorizontalAlignment = xlCenter
Cells.Interior.Pattern = xlSolid
Cells.Interior.TintAndShade = -0.0499893185216834
Range("A1:B1,E1:F1").Interior.ThemeColor = xlThemeColorLight1
Range("A:B,E:F").Borders.LineStyle = xlContinuous
Range("A1:B1,E1:F1").Font.ThemeColor = xlThemeColorDark1
Range("A1:B1,E1:F1").Font.Bold = True
Application.Goto Reference:=Range("A1"), Scroll:=True
' Breakdown Sheet
Sheets("Breakdown").Activate
Cells.NumberFormat = "#"
wbksaved.Sheets("MVRT").UsedRange.Columns("A:D").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "A").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("F:F").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "E").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("H:H").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "F").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("N:N").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "G").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("S:S").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "H").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("K:K").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "I").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("J:J").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "J").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("M:M").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "K").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("Q:Q").SpecialCells(xlCellTypeVisible).Copy
ActiveSheet.Paste Destination:=Worksheets("Breakdown").Range("L:L")
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
'Range("O:P").Delete
Range("A1").Value = "UUID"
Range("B1").Value = "Security Code"
Range("C1").Value = "Customer Code"
Range("D1").Value = "Country Code"
Range("E1").Value = "Salesforce Id"
Range("F1").Value = "Merchant Name"
Range("G1").Value = "Unit Status"
Range("H1").Value = "Redemption Status"
Range("I1").Value = "Expires At"
Range("J1").Value = "Expired"
Range("K1").Value = "Suspended"
Range("L1").Value = "Redemption Date"
'Range("M:M").Replace What:="Invalid Rights", Replacement:="Other Country"
Range("B:L").Sort Key1:=Range("I:I"), Order1:=xlAscending, Header:=xlYes
Range("A:L").EntireColumn.AutoFit
Range("A1:L1").HorizontalAlignment = xlCenter
Cells.Interior.Pattern = xlSolid
Cells.Interior.TintAndShade = -0.0499893185216834
Range("A1:L1").Interior.ThemeColor = xlThemeColorLight1
Range("A:L").Borders.LineStyle = xlContinuous
Range("A1:L1").Font.ThemeColor = xlThemeColorDark1
Rows("1:1").Font.Bold = True
Application.Goto Reference:=Range("A1"), Scroll:=True
'Summary Sheet
Sheets("Summary").Activate
Range("C9").Value = "Country"
Range("C10").Value = "Merchant Name"
Range("C11").Value = "Type"
Range("C16").Value = "Redemption Type"
Range("C17").Value = "Invalid"
Range("C18").Value = "Duplicates"
Range("C19").Value = "Suspended"
Range("C20").Value = "Voucher Expired"
Range("C21").Value = "Payment Invalid"
Range("C22").Value = "Payment Refunded"
Range("C23").Value = "Redeemed"
Range("C24").Value = "Total Codes Sent In"
Range("D9").FormulaR1C1 = "=Breakdown!R[-7]C[0]"
Range("D10").FormulaR1C1 = "=Breakdown!R[-8]C[2]"
Range("D11").FormulaR1C1 = "Offsite Redemptions"
Range("D16").FormulaR1C1 = "No."
Range("D17").FormulaR1C1 = "=COUNTA('Duplicates,Invalid'!C[2])-1"
Range("D18").FormulaR1C1 = "=COUNTA('Duplicates,Invalid'!C[-2])-1"
Range("D19").Formula = "=COUNTIFS(Breakdown!K:K,""*true*"",Breakdown!H:H,""*Forced redeemable*"")"
'Range("D19").AutoFill Destination:=Range("D19:D25"), Type:=xlFillCopy
Range("D20").Formula = "=COUNTIFS(Breakdown!J:J,""*true*"",Breakdown!K:K,""*false*"",Breakdown!G:G,""*collected*"",Breakdown!H:H,""*Forced redeemable*"")"
'payment not received:
Range("D21").Formula = "=COUNTIFS(Breakdown!K:K,""*false*"",Breakdown!G:G,""*resigned*"",Breakdown!H:H,""*Forced redeemable*"") + COUNTIFS(Breakdown!K:K,""*false*"",Breakdown!G:G,""*pending*"",Breakdown!H:H,""*Forced redeemable*"")"
'payment refunded:
Range("D22").Formula = "=COUNTIFS(Breakdown!G:G,""*deleted*"",Breakdown!K:K,""*false*"",Breakdown!H:H,""*Forced redeemable*"")"
Range("D23").Formula = "=COUNTIF(Breakdown!H:H,""*redeemed*"")"
'sum-formula:
Range("D24").Formula = "=COUNTA(Breakdown!A:A)-1 + SUM(D17:D18)"
Range("C:D").Copy
Range("C:C").PasteSpecial xlPasteValues
Application.CutCopyMode = False
Range("A:B,E:F").ColumnWidth = 26
Range("C:D").ColumnWidth = 63.29
Range("C:D").HorizontalAlignment = xlCenter
Cells.Interior.Pattern = xlSolid
Cells.Interior.TintAndShade = -0.0499893185216834
Range("C1:D5,C9:C11,C16:D16,C24:D24").Interior.ThemeColor =
xlThemeColorLight1
Range("D9:D11,C16:D24").Borders.LineStyle = xlContinuous
Range("C9:C11,C16:D16,C24:D24").Font.ThemeColor = xlThemeColorDark1
Range("C9:D11,C16:D24").Font.Bold = True
Range("C3:D3").Merge True
Dim myR As Range
Set myR = Range("C3:D3")
wbksaved.Sheets("Control").Shapes("Groupon Logo").Copy
Range("C3:D3").PasteSpecial xlPasteFormats
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
Selection.ShapeRange.ScaleWidth 1, msoFalse, msoScaleFromTopLeft
Selection.ShapeRange.ScaleHeight 1, msoFalse, msoScaleFromTopLeft
Selection.ShapeRange.IncrementLeft (myR.Width - Selection.ShapeRange.Width) / 2
Application.Goto Reference:=Range("A1"), Scroll:=True
Country = Range("D9").Value
'Merchant_ID = Range("D10").Value This was DELETED on Lorene request
Merchant_Name = Range("D10").Value
dt = Format(CStr(Now), "dd_mm_yyyy_hh_mm_ss")
File_Name = File_path & "\" & "Report" & " " & Merchant_Name & " " &
Merchant_ID & " " & dt & ".xlsx"
ActiveWorkbook.SaveAs Filename:=File_Name, FileFormat:=51
ActiveWorkbook.Close
Application.DisplayAlerts = False
Sheets("Data").Cells.Delete
Application.DisplayAlerts = True
Sheets("Control").Select
MsgBox "Report Created", vbInformation, "Report Created"
Application.ScreenUpdating = True
End Sub
Can you try instead of this:
ActiveSheet.UsedRange.Columns("A:T").SpecialCells(xlCellTypeVisible).Select
Selection.Copy
wbksaved.Sheets("Data").Paste
To write this:
ActiveSheet.Columns("A:T").SpecialCells(xlCellTypeVisible).Copy
wbksaved.Sheets("Data").Range("A1").Paste
And to see whether the "error" would still exist? In general, Selection.Copy and ActiveSheet, ActiveCell should be avoided whenever possible - How to avoid using Select in Excel VBA

Changing all cells in a column with dropdown lists

I'm trying to replace all cells in a column with a dropdown list for using an excel macro. I'm also trying to use dynamic range as I don't know how long the list is at all times. This is my code as of right now:
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = Worksheets("*Name of main sheet*")
Set StartCell = Range("A1")
'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
'Select Range
Worksheets("*Name of main sheet*").Activate
'replace "J2" with the cell you want to insert the drop down list
With Range(StartCell, sht.Cells(LastRow, LastColumn))
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=Sheet1!A1:A6"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
I'm creating the lists with all the options for the drop down in a separate tab called Sheet1.
add .Validation at the end of With Range(StartCell, sht.Cells(LastRow, LastColumn)) and use $ to keep rows reference fixed
so the whole With-End block With becomes:
With Range(StartCell, sht.Cells(LastRow, LastColumn)).Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=Sheet1!A$1:A$6"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
if you need to keep dropdowns list dynamic with Sheet1 column A not blank values then you could go as follows:
Dim LastRow As Long
Dim LastColumn As Long
Dim sourceSht As Worksheet
Set sourceSht = Worksheets("Sheet1")
With Worksheets("Name of main sheet")
LastRow = .Cells(.Rows.Count, 1).End(xlUp).row
LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
With .Range("A1", .Cells(LastRow, LastColumn)).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=" & sourceSht.name & "!" & sourceSht.Range("A1", sourceSht.Cells(sourceSht.Rows.Count, 1).End(xlUp)).Address(True, False)
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End With

User form to define data validation list range excel

I have a button that once clicked loops through a DV list and prints each selection as a PDF document, ideally id like to be able to choose the length of the DV list via a Userform EG I select option one on the userform which sets the DV list range to 50 cells.
Sub Button_Click6()
Dim cell As Excel.Range
Dim rgDV As Excel.Range
Dim DV_Cell As Excel.Range
Dim LA As Boolean
Set ws = ActiveSheet
LAform.Show
Select Case LAform.Tag
Case 0
LA = False 'FALSE FOR Richmond, TRUE FOR Kingston
Case 1
LA = True
End Select
If LA = True Then
ActiveSheet.Range("B1").Validation.Add xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=Worksheets("Data").Range("B4:B56")
ElseIf LA = False Then
ActiveSheet.Range("B1").Validation.Add xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=Worksheets("Data").Range("B56:B104")
'enter name and select folder for file
' start in current workbook folder
Set DV_Cell = Range("B1")
Set rgDV = Application.Range(Mid$(DV_Cell.Validation.Formula1, 2))
For Each cell In rgDV.Cells
DV_Cell.Value = cell.Value
Call PDFActiveSheet2
Next
End If
End Sub
The problem i get is an Application or object defined error After the If and else if trying to set the dv range.
Thanks.
Sub Button_Click6()
Dim cell As Excel.Range
Dim rgDV As Excel.Range
Dim DV_Cell As Excel.Range
Dim La As Boolean
Laform.Show
Select Case Laform.Tag
Case 0
La = False 'FALSE FOR Richmond, TRUE FOR Kingston
Case 1
La = True
End Select
Set DV_Cell = Range("B1")
Set rgDV = Application.Range(Mid$(DV_Cell.Validation.Formula1, 2))
For Each cell In rgDV.Cells
DV_Cell.Value = cell.Value
Call PDFActiveSheet2
Next
End Sub
With the advice i was given i put the code into the user form buttons which sets the DV list range, while the macro runs as it now should.
Private Sub Borough1_Click()
Range("B1:E1").Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=Data!$B$57:$B$107"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Me.Hide
End Sub
Private Sub CommandButton1_Click()
Range("B1:E1").Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=Data!$B$4:$B$56"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Me.Hide
End Sub

Excel VBA drop down list and vlookup issue

I am trying to make a VBA code that will create a drop down list or have a Vlookup function in a cell.
I am new to VBA so please have mercy. :)
The problem is that with the code below it always crashes Excel.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Lookup_Range As Range
Set shList = ThisWorkbook.Sheets("ListaEchipamente")
Set Lookup_Range = shList.Range("G10", "M345")
If Cells(Target.Row, 13).Value = " " Then
With Range("J2:J100").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=ListaEchipamente!K10:K345"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
ElseIf Not Cells(Target.Row, 13).Value = " " Then
Cells(Target.Row, 10).Value = "=VLookup(Range(target.row, 13), Lookup_Range, 2, False)"
End If
End Sub
Thank you for the help.
Your code changing Cells(Target.Row, 10).Value triggers another Change event and you get endless loop. To avoid it disable events first:
Application.EnableEvents = False
'code to modify cells here
Application.EnableEvents = True