Worksheet Codename Errors - vba

When using the code below to reference a worksheet by codename, I get file explorer opening up for each instance of the "Sheet34". How can I prevent this?
Private Sub CheckBox4_Click()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim sheetName As String
If CheckBox4.Value = True Then
ActiveWorkbook.Unprotect
Worksheets("SUMMARY").Unprotect
sheetName = Sheets("Control").Cells(16, "I")
If sheetName = "" Then
MsgBox "You must enter a valid Allowance descriptor. No entry was detected."
CheckBox4.Value = False
Exit Sub
End If
If Len(sheetName) > 31 Then
MsgBox "Worksheet tab names cannot be greater than 31 characters in length."
Application.EnableEvents = False
Sheets("Control").Cells(16, "I").ClearContents
Application.EnableEvents = True
CheckBox4.Value = False
Exit Sub
End If
Dim IllegalCharacter(1 To 7) As String, i As Integer
IllegalCharacter(1) = "/"
IllegalCharacter(2) = "\"
IllegalCharacter(3) = "["
IllegalCharacter(4) = "]"
IllegalCharacter(5) = "*"
IllegalCharacter(6) = "?"
IllegalCharacter(7) = ":"
For i = 1 To 7
If InStr(sheetName, (IllegalCharacter(i))) > 0 Then
MsgBox "You used a character that violates sheet naming rules. Please refrain from the following characters: / \ [ ] * ? : "
Application.EnableEvents = False
Sheets("Control").Cells(16, "I").ClearContents
Application.EnableEvents = True
CheckBox4.Value = False
Exit Sub
End If
Next i
If Sheets("Control").Range("I16") = Sheets("Control").Range("I17") Then
MsgBox "There is already an Allowance with this name. Please choose a different name."
Application.EnableEvents = False
Sheets("Control").Cells(16, "I").ClearContents
Application.EnableEvents = True
CheckBox4.Value = False
Exit Sub
End If
If Sheets("Control").Range("I16") = Sheets("Control").Range("I18") Then
MsgBox "There is already an Allowance with this name. Please choose a different name."
Application.EnableEvents = False
Sheets("Control").Cells(16, "I").ClearContents
Application.EnableEvents = True
CheckBox4.Value = False
Exit Sub
End If
If Sheets("Control").Range("I16") = Sheets("Control").Range("I21") Then
MsgBox "There is already an Other Item with this name. Please choose a different name."
Application.EnableEvents = False
Sheets("Control").Cells(16, "I").ClearContents
Application.EnableEvents = True
CheckBox4.Value = False
Exit Sub
End If
If Sheets("Control").Range("I16") = Sheets("Control").Range("I22") Then
MsgBox "There is already an Other Item with this name. Please choose a different name."
Application.EnableEvents = False
Sheets("Control").Cells(16, "I").ClearContents
Application.EnableEvents = True
CheckBox4.Value = False
Exit Sub
End If
If Sheets("Control").Range("I16") = Sheets("Control").Range("I23") Then
MsgBox "There is already an Other Item with this name. Please choose a different name."
Application.EnableEvents = False
Sheets("Control").Cells(16, "I").ClearContents
Application.EnableEvents = True
CheckBox4.Value = False
Exit Sub
End If
If WorksheetExists(sheetName) Then
Worksheets(sheetName).Visible = -1
Worksheets("SUMMARY").Rows("47").EntireRow.Hidden = False
Worksheets("SUMMARY").Cells(47, 2).Value = "ALL 1:"
Worksheets("SUMMARY").Cells(47, 3).Value = "='Control'!I16"
Worksheets("SUMMARY").Cells(47, 3).NumberFormat = "General"
Worksheets("SUMMARY").Cells(47, 4).Value = "='Control'!K16"
Worksheets("SUMMARY").Cells(47, 5).Value = "='Control'!L16"
Worksheets("SUMMARY").Cells(47, 6).Value = "=" & sheetName & "!$H$69"
Worksheets("SUMMARY").Cells(47, 7).Value = "=" & sheetName & "!$J$69"
Worksheets("SUMMARY").Cells(47, 8).Value = "=" & sheetName & "!$N$69"
Worksheets("SUMMARY").Cells(47, 9).Value = "=" & sheetName & "!$P$69"
Worksheets("SUMMARY").Cells(47, 10).Value = "=SUM(F47:I47)/D47"
Worksheets("SUMMARY").Cells(47, 11).Value = "=L47/F3"
Worksheets("SUMMARY").Cells(47, 12).Value = "=" & sheetName & "!$U$69"
Worksheets("SUMMARY").Cells(47, 13).Value = "=L47/$K$57"
ActiveWorkbook.Protect
Sheets(sheetName).Protect
Sheets("SUMMARY").Protect
Exit Sub
Else
Set ws = ActiveWorkbook.Sheet34
ws.Name = sheetName
ws.Protect
ws.EnableSelection = xlUnlockedCells
Application.CutCopyMode = False
Worksheets("SUMMARY").Rows("47").EntireRow.Hidden = False
Worksheets("SUMMARY").Cells(47, 2).Value = "ALL 1:"
Worksheets("SUMMARY").Cells(47, 3).Value = "='Control'!I16"
Worksheets("SUMMARY").Cells(47, 3).NumberFormat = "General"
Worksheets("SUMMARY").Cells(47, 4).Value = "='Control'!K16"
Worksheets("SUMMARY").Cells(47, 5).Value = "='Control'!L16"
Worksheets("SUMMARY").Cells(47, 6).Value = "=" & ws.Name & "!$H$69"
Worksheets("SUMMARY").Cells(47, 7).Value = "=" & ws.Name & "!$J$69"
Worksheets("SUMMARY").Cells(47, 8).Value = "=" & ws.Name & "!$N$69"
Worksheets("SUMMARY").Cells(47, 9).Value = "=" & ws.Name & "!$P$69"
Worksheets("SUMMARY").Cells(47, 10).Value = "=SUM(F47:I47)/D47"
Worksheets("SUMMARY").Cells(47, 11).Value = "=L47/F3"
Worksheets("SUMMARY").Cells(47, 12).Value = "=" & ws.Name & "!$U$69"
Worksheets("SUMMARY").Cells(47, 13).Value = "=L47/$K$57"
ActiveWorkbook.Protect
Sheets(sheetName).Protect
Sheets("SUMMARY").Protect
Worksheets("Control").Activate
End If
End If
If CheckBox4.Value = False Then
ActiveWorkbook.Unprotect
Worksheets("SUMMARY").Unprotect
sheetName = Sheets("Control").Cells(16, "I")
If WorksheetExists(sheetName) Then
Worksheets(sheetName).Visible = 2
Worksheets("SUMMARY").Rows("47").EntireRow.ClearContents
Worksheets("SUMMARY").Rows("47").EntireRow.Hidden = True
ActiveWorkbook.Protect
Sheets(sheetName).Protect
Sheets("SUMMARY").Protect
End If
End If
Application.ScreenUpdating = True
End Sub
Follow up question: This code is taking an existing sheet and renaming it. The concern I have is if the user names the sheet in Cell I16, then renames it, and unchecks or checks the box, I get a row on the Summary Worksheet with poor references. Also, the code will not allow me to enter the code below
Worksheets("SUMMARY").Cells(47, 6).Value = "=" & sheetName & "!$H$69"
as
Worksheets("SUMMARY").Cells(47, 6).Value = "="' & sheetName & '"!$H$69"
as it turns the & sheetName & into a comment. How can I fix this so that the worksheet is properly referenced in the code? Do I need to keep with the codename worksheet?
My thoughts on how to stop the renaming issue was to protect the named cell so long as the checkbox value is positive, and allow the user to edit the cell if the checkbox value is false; maybe adding a line of code that checks if the cell is being changed and asking the user if they are sure this is the cell they want to modify, which would clear the data, but not the formatting, of the existing spreadsheet.

You are trying to set the value of a cell to a formula...Try out the following:
Create a direct link to a cell in another sheet within the same workbook
Open another workbook.
Create a direct link to a cell in a sheet from the other workbook
You will find that the following would be correct use for a worksheet reference:
Worksheets("SUMMARY").Cells(47, 6).Formula = "='" & sheetName & "'!$H$69"
And the below for a workbook reference:
Worksheets("SUMMARY").Cells(47, 6).Formula = "='[" & Worboookpath & "] & sheetName & "'!$H$69"

Related

Keep Receiving a 424 Debug Error w/ File Name

Please see the bold code below. The debugger says that it is what's causing the 424 "Object Required" error. Any insight/help on this would be greatly appreciated.
Sub GraywolfPlanful()
Dim sForecastFile, sUploadFile, sTab As String
Dim i As Integer
Application.ScreenUpdating = False
sForecastFile = GraywolfWorkbook.Name
Workbooks.Add
sUploadFile = GraywolfWorkbook.Name
Range("A1") = "Company"
Range("B1") = "Department"
Range("C1") = "Location"
Range("D1") = "Segment"
Range("E1") = "Account"
Range("F1") = "Year"
Range("G1") = "Month"
Range("H1") = "Amount"
Range("A2").Select
Windows(sForecastFile).Activate
sTab = Format(Sheets("00_No Department").Range("C1"), "yyyy-mm mmm") & "Project Forecast"
For i = 4 To Sheets.Count
Sheets(i).Select
Range("F6").Select
Do Until (Range("C") = "End" And Range("D") = "Subtotal Other G&A")
If Range("Z" & ActiveCell.Row) <> "" Then
Range("Z" & ActiveCell.Row, "AD" & ActiveCell.Row).Copy
Windows(sUploadFile).Activate
Range(ActiveCell, ActiveCell.Offset(12, 0)).PasteSpecial xlPasteValues
Range("B" & ActiveCell.Row, "B" & ActiveCell.Row + 12) = "Test"
Windows(sCurrentFile).Activate
End If
Loop
Next i
Windows(sUploadFile).Activate
GraywolfWorkbook.SaveAs CurDir & "\Test File Graywolf"
Application.ScreenUpdating = True
End Sub

Lag in vba vlookup

I'm running VBA code using vlookup, however, it take a few seconds to complete, despite the sheet that has the rows only has less than 150 rows.
The lag mainly appears during the generation of col 23.
The main sheet that contains this code has about 2300 rows.
Is the lag normal or is my coding inefficiency getting the best of me?
Private Sub Worksheet_Change(ByVal Target As Range)
thisrow = Target.Row
If Target.Column = 21 Then
' Generate the problem comments
' Declare some variables
Dim CodeString As String
Dim codeArr() As String
Dim isPI As Boolean
isPI = False
' Reset the impact, comment and origin cells
Cells(thisrow, 22).Value = ""
Cells(thisrow, 23).Value = ""
Cells(thisrow, 25).Value = ""
' For esthetics, remove spaces in the cell
Application.EnableEvents = False
Cells(thisrow, 21).Value = Replace(Cells(thisrow, 21).Value, " ", "")
Application.EnableEvents = True
' Get the code(s)
CodeString = Cells(thisrow, 21).Value
codeArr = Split(CodeString, Chr(59))
' Error code rows
ErrLastRow = Sheets("lookup error codes").Cells(Sheets("lookup error codes").Rows.Count, 1).End(xlUp).Row
' There's more than one code
If UBound(codeArr) > 0 Then
For i = 0 To UBound(codeArr)
If i < UBound(codeArr) Then
Cells(thisrow, 23).Value = Cells(thisrow, 23).Value & Application.WorksheetFunction.VLookup(CInt(codeArr(i)), Sheets("lookup error codes").Range("$A$2:$C$" & ErrLastRow).Value, 2, False) & "; "
Else
Cells(thisrow, 23).Value = Cells(thisrow, 23).Value & Application.WorksheetFunction.VLookup(CInt(codeArr(i)), Sheets("lookup error codes").Range("$A$2:$C$" & ErrLastRow).Value, 2, False)
End If
Next i
' Check to see if anything is pay impacting
For Each code In codeArr
If Application.WorksheetFunction.VLookup(CInt(code), Sheets("lookup error codes").Range("$A$2:$C$" & ErrLastRow).Value, 3, False) <> "" Then
isPI = True
' We only needed one
Exit For
End If
Next code
Else
' There's only one code
Cells(thisrow, 23).Value = Application.WorksheetFunction.VLookup(Cells(thisrow, 21).Value, Sheets("lookup error codes").Range("$A$2:$C$" & ErrLastRow).Value, 2, False)
If Application.WorksheetFunction.VLookup(Cells(thisrow, 21).Value, Sheets("lookup error codes").Range("$A$2:$C$" & ErrLastRow).Value, 3, False) <> "" Then
isPI = True
End If
End If
' There is a code that is pay impacting
If isPI = True Then
Cells(thisrow, 22).Value = "X"
End If
' Modify the origin of error with common origins
Dim Comment As Range, OrigErr As Range
Set Comment = Range(Cells(thisrow, 23).Address)
Set OrigErr = Range(Cells(thisrow, 25).Address)
OrigErr.Value = ""
If InStr(1, Comment.Value, "aaa", vbBinaryCompare) Or _
InStr(1, Comment.Value, "bbb", vbBinaryCompare) Or _
InStr(1, Comment.Value, "ccc", vbBinaryCompare) Then
OrigErr.Value = "ddd"
ElseIf InStr(1, Comment.Value, "eee", vbBinaryCompare) Then
OrigErr.Value = "fff"
End If
End If
End Sub
Changing a cell's value to "" is triggering a change event. Disable events before changing anything on the worksheet and disable calculation if the changed cells affect other formulas.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
If Target.Column = 21 Then
' Generate the problem comments
' Declare some variables
Dim CodeString As String, codeArr As Variant
Dim isPI As Boolean, thisRow As Long
On Error GoTo safe_exit
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
thisRow = Target.Row
isPI = False
' Reset the impact, comment and origin cells
Cells(thisRow, 22) = vbNullString
Cells(thisRow, 23).Value = vbNullString
Cells(thisRow, 25).Value = vbNullString
' For esthetics, remove spaces in the cell
Cells(thisRow, 21) = Replace(Cells(thisRow, 21).Value, " ", vbNullString)
' Get the code(s)
CodeString = Cells(thisRow, 21).Value
codeArr = Split(CodeString, Chr(59))
' Error code rows
ErrLastRow = Sheets("lookup error codes").Cells(Sheets("lookup error codes").Rows.Count, 1).End(xlUp).Row
' Doesn't matter if there is one code or many
For i = LBound(codeArr) To UBound(codeArr)
If i < UBound(codeArr) Then
Cells(thisRow, 23).Value = Cells(thisRow, 23).Value & Application.VLookup(CLng(codeArr(i)), Sheets("lookup error codes").Range("A:C"), 2, False) & "; "
Else
Cells(thisRow, 23).Value = Cells(thisRow, 23).Value & Application.VLookup(CLng(codeArr(i)), Sheets("lookup error codes").Range("A:C"), 2, False)
End If
Next i
' Check to see if anything is pay impacting
For Each code In codeArr
If Application.VLookup(CLng(code), Sheets("lookup error codes").Range("A:C"), 3, False) <> "" Then
' There is a code that is pay impacting
Cells(thisRow, 22).Value = "X"
' We only needed one
Exit For
End If
Next code
If isPI Then
End If
' Modify the origin of error with common origins
Dim Comment As Range, OrigErr As Range
Set Comment = Cells(thisRow, 23)
Set OrigErr = Cells(thisRow, 25)
OrigErr.Value = vbNullString
If InStr(1, Comment.Value, "aaa", vbBinaryCompare) Or _
InStr(1, Comment.Value, "bbb", vbBinaryCompare) Or _
InStr(1, Comment.Value, "ccc", vbBinaryCompare) Then
OrigErr.Value = "ddd"
ElseIf InStr(1, Comment.Value, "eee", vbBinaryCompare) Then
OrigErr.Value = "fff"
End If
End If
safe_exit:
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
Add
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
To the start of your code and
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
to the end.

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

Error with Checkbox and Duplicate Sheets

I have designed a code that creates a new worksheet based on a checkbox, and the name is derived from a User Defined Variable. However, if someone unchecks and checks the box, it runs the code again and generates an error due to multiple worksheets having the same name. I understand that this is just the code functioning as it is supposed to, but I want to create an IF:THEN statement where the code checks to see if the name exists. If the sheet exists, the code will do stop itself; if the sheet does not exist, it will run as normal.
How can I do this?
Code below.
Private Sub CheckBox4_Click()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim Protocol As Range
If CheckBox4.Value = True Then
ActiveWorkbook.Unprotect
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
ws.Name = Sheets("Control").Cells(16, "I")
Set Protocol = Sheets("The Hidden Works").Columns("W:AQ").EntireColumn
Protocol.Copy
ws.Paste
ws.Protect
ws.EnableSelection = xlUnlockedCells
Application.CutCopyMode = False
Worksheets("SUMMARY").Rows("44").EntireRow.Hidden = False
Worksheets("SUMMARY").Cells(44, 3).Value = "='Control'!I16"
Worksheets("SUMMARY").Cells(44, 3).NumberFormat = "General"
Worksheets("SUMMARY").Cells(44, 4).Value = "='Control'!K16"
Worksheets("SUMMARY").Cells(44, 5).Value = "='Control'!L16"
Worksheets("SUMMARY").Cells(44, 6).Value = "=" & ws.Name & "!$H$69"
Worksheets("SUMMARY").Cells(44, 7).Value = "=" & ws.Name & "!$J$69"
Worksheets("SUMMARY").Cells(44, 8).Value = "=" & ws.Name & "!$N$69"
Worksheets("SUMMARY").Cells(44, 9).Value = "=" & ws.Name & "!$P$69"
Worksheets("SUMMARY").Cells(44, 10).Value = "=SUM(F44:I44)/D44"
Worksheets("SUMMARY").Cells(44, 11).Value = "=M44/F3"
Worksheets("SUMMARY").Cells(44, 12).Value = "=" & ws.Name & "!$U$69"
Worksheets("SUMMARY").Cells(44, 13).Value = "=M44/$K$57"
Worksheets("Control").Activate
End If
Application.ScreenUpdating = True
End Sub
You can evaluate if a cell exists on the specifically named sheet to check:
Application.DisplayAlerts = False
If IsError(Evaluate("SHEETNAME!A1")) Then Sheets.Add(After:=Sheets(Sheets.Count)).Name = "SHEETNAME"
Application.DisplayAlerts = True
You can use the below function to check if a Sheet exists:
Function WorksheetExists(sheetName As String) As Boolean
WorksheetExists = Evaluate("ISREF('" & sheetName & "'!A1)")
End Function
Use it like,
If WorksheetExists("Sheet10") Then
Exit Sub
Else
'Your Code
End If
Your code adapted to use the solution:
Private Sub CheckBox4_Click()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim Protocol As Range
Dim sheetName As String
If CheckBox4.Value = True Then
ActiveWorkbook.Unprotect
sheetName = Sheets("Control").Cells(16, "I")
If WorksheetExists(sheetName) Then
Exit Sub
Else
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
ws.Name = sheetName
Set Protocol = Sheets("The Hidden Works").Columns("W:AQ").EntireColumn
Protocol.Copy
ws.Paste
ws.Protect
ws.EnableSelection = xlUnlockedCells
Application.CutCopyMode = False
Worksheets("SUMMARY").Rows("44").EntireRow.Hidden = False
Worksheets("SUMMARY").Cells(44, 3).Value = "='Control'!I16"
Worksheets("SUMMARY").Cells(44, 3).NumberFormat = "General"
Worksheets("SUMMARY").Cells(44, 4).Value = "='Control'!K16"
Worksheets("SUMMARY").Cells(44, 5).Value = "='Control'!L16"
Worksheets("SUMMARY").Cells(44, 6).Value = "=" & ws.Name & "!$H$69"
Worksheets("SUMMARY").Cells(44, 7).Value = "=" & ws.Name & "!$J$69"
Worksheets("SUMMARY").Cells(44, 8).Value = "=" & ws.Name & "!$N$69"
Worksheets("SUMMARY").Cells(44, 9).Value = "=" & ws.Name & "!$P$69"
Worksheets("SUMMARY").Cells(44, 10).Value = "=SUM(F44:I44)/D44"
Worksheets("SUMMARY").Cells(44, 11).Value = "=M44/F3"
Worksheets("SUMMARY").Cells(44, 12).Value = "=" & ws.Name & "!$U$69"
Worksheets("SUMMARY").Cells(44, 13).Value = "=M44/$K$57"
Worksheets("Control").Activate
End If
End If
Application.ScreenUpdating = True
End Sub
Function WorksheetExists(sheetName As String) As Boolean
WorksheetExists = Evaluate("ISREF('" & sheetName & "'!A1)")
End Function

VBA Programming. Error or Prompt will appear in Userform if field in sheet already has content

I wanted to have a code wherein there will be an error or prompt in the userform if the cell in the sheet- wherein the data will be transferred, already has content. As of now, the code I'm using doesn't show any prompt but it succeeds in not updating the cell if a data is to be transferred to it again.
Private Sub CancelButton_Click()
Unload Me
End Sub
Private Sub ClearButton_Click()
Call UserForm_Initialize
End Sub
Private Sub OKButton_Click()
Dim emptyRow As Long
'Make Sheet1 active
Sheet1.Activate
'Determine emptyRow
Dim rFound As Range: Set rFound = Range("B:B").Find(BarcodeTextBox.Value, , , xlWhole)
If rFound Is Nothing Then
emptyRow = Range("B" & Rows.Count).End(xlUp).Row + 1
Else
emptyRow = rFound.Row
End If
'Transfer information
If TimeOptionButton1.Value = True Then
Cells(emptyRow, 5).Value = "Yes"
End If
If TimeOptionButton2.Value = True Then
Cells(emptyRow, 7).Value = "Yes"
End If
If BreakOptionButton1.Value = True Then
Cells(emptyRow, 9).Value = "Yes"
End If
If BreakOptionButton2.Value = True Then
Cells(emptyRow, 11).Value = "Yes"
End If
If BreakOptionButton3.Value = True Then
Cells(emptyRow, 14).Value = "Yes"
End If
If BreakOptionButton4.Value = True Then
Cells(emptyRow, 16).Value = "Yes"
End If
Cells(emptyRow, 2).Value = BarcodeTextBox.Value
Set ws = ActiveSheet
Me.TextBox1 = Application.WorksheetFunction. _
CountIf(ws.Range("$T$2:$E$977"), "IN")
Me.TextBox2 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "LF")
Me.TextBox3 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "READYMAN")
Me.TextBox4 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "B-MIRK")
Me.TextBox5 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "VISITOR")
End Sub
Private Sub UserForm_Initialize()
'Set Time In as default
TimeOptionButton1.Value = True
'Empty BarcodeTextBox
BarcodeTextBox.Value = ""
Set ws = ActiveSheet
Me.TextBox1 = Application.WorksheetFunction. _
CountIf(ws.Range("$T$2:$E$977"), "IN")
Me.TextBox2 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "LF")
Me.TextBox3 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "READYMAN")
Me.TextBox4 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "B-MIRK")
Me.TextBox5 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "VISITOR")
End Sub
Thank you in advance!
Concerning your code, I think that you may add something like this:
If TimeOptionButton1.Value = True Then
if len(cells(emptyRow,5)) = 0 then
MsgBox "Write Error Message here"
else
Cells(emptyRow, 5).Value = "Yes"
end if
End If
For each yes. You may consider building a separate function/sub later to avoid repetition.