Error with Checkbox and Duplicate Sheets - vba

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

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

Worksheet Codename Errors

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"

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.

excel vba code corrupting my file consistently after a few runs

I have a relatively long set of subs that get run on a list of my excel files a few times a day. after a few runs, the file then becomes corrupted which normally would not be an issue b/c it doesn't really effect any of the data. however, I have another program that opens up each of the excel and pulls some key data from each one to make a summary sheet. because the corrupted file gives a message that says something along the lines of "there is a problem with some of your content" the summary program stops with a
run-time error '1004': Method of object 'Workbooks' Failed
I can not for the life of me figure out what in my code is causing the corruption. Is there a way I can have the summary code ignore the corruption notification? Ive tried a handful of different things including turning the application notifications off in my code to no avail.
Any help is greatly appreciated! ill post my all my code with a brief description below:
Here is the code from the summary file that opens each of the
individual files and pulls data:
Sub OEEsummmary()
Dim ActCycCell, ExpCycCell, ExpCurCycCell, ShiftCell, DifCell, DownCell, DTResACell, DTResBCell, PartCell, OpNamCell, OprCell, RejCell, RejResCell As Range
Dim MySheet As Worksheet
Dim Txt$, MyPath$, MyWB$
Dim myValue As Integer
Dim x As Long
Dim v As Variant, r As Range, rWhere As Range
MyPath = "L:\Manufacturing Engineering\Samuel Hatcher\"
x = 2
Set MySheet = ActiveSheet
'Application.ScreenUpdating = False
Application.EnableEvents = False
MySheet.Range("B2:G18").ClearContents
MySheet.Range("J2:O18").ClearContents
Do While MySheet.Range("A" & x).Value <> ""
MyWB = MySheet.Range("A" & x).Text
Workbooks.Open Filename:=MyPath & MyWB, ReadOnly:=True, IgnoreReadOnlyRecommended:=True
Set ActCycCell = ActiveSheet.Range("E21")
Set ExpCycCell = ActiveSheet.Range("D21")
Set ShiftCell = ActiveSheet.Range("E2")
Set DownCell = ActiveSheet.Range("K28")
Set DTResACell = ActiveWorkbook.Worksheets("Downtime").Range("O9")
Set DTResBCell = ActiveWorkbook.Worksheets("Downtime").Range("O10")
Set PartCell = ActiveSheet.Range("E4")
Set ExpCurCycCell = ActiveSheet.Range("D22")
If ActiveSheet.Range("I3") = "" Then
Set OpNamCell = ActiveSheet.Range("I2")
Else
Set OpNamCell = ActiveSheet.Range("I3")
End If
Set OprCell = ActiveSheet.Range("C4")
Set RejCell = ActiveSheet.Range("H21")
Set RejResCell = ActiveWorkbook.Worksheets("Rejected Parts").Range("H5")
With MySheet.Range("A" & x)
.Offset(0, 14).Value = OprCell.Value
.Offset(0, 13).Value = OpNamCell.Value
.Offset(0, 12).Value = PartCell.Value
.Offset(0, 11).Value = ShiftCell.Value
.Offset(0, 10).Value = RejResCell.Value
.Offset(0, 9).Value = RejCell.Value
.Offset(0, 6).Value = ActCycCell.Value
.Offset(0, 5).Value = ExpCycCell.Value
.Offset(0, 4).Value = ExpCurCycCell.Value
.Offset(0, 3).Value = DTResBCell.Value
.Offset(0, 2).Value = DTResACell.Value
.Offset(0, 1).Value = DownCell.Value
End With
ActiveWorkbook.Close savechanges:=False
x = x + 1
Loop
Call sort
'Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Clears the page of data to prepare it for a new shift of entering
data:
Sub ClearFrontEnd()
Sheets("Front End").Unprotect ("29745")
'prompts user to confirm if they realy want to clear entry
response = MsgBox("Are You Sure?", vbYesNo)
If response = vbNo Then
Exit Sub
End If
'checks to see if operator number is there
If range("I3").Value = "" Then
MsgBox "ENTER OPORATOR # AND CLICK NEW SHIFT AGAIN"
Else
Call StopTimer
Call prodChoose
Call transfer
Application.ScreenUpdating = False
ActiveWorkbook.Save
Sheets("Front End").Unprotect ("29745")
Sheets("Front End").Select
'Deletes the data from the entry and unique key fields
range("E8:E20").ClearContents
range("I8:I27").ClearContents
range("J8:J27").ClearContents
range("K8:K27").ClearContents
range("I3").ClearContents
range("H8").Value = ""
range("H9").Value = ""
range("H10").Value = ""
range("H11").Value = ""
range("H12").Value = ""
range("H13").Value = ""
range("H14").Value = ""
range("H15").Value = ""
range("H16").Value = ""
range("H17").Value = ""
range("H18").Value = ""
range("H19").Value = ""
range("H20").Value = ""
range("A1").Select
MsgBox "Please enter the correct values for SHIFT #, SHIFT LENGTH, PART #, AND OPORATOR #, Thanks! Have a great day!!"
End If
Sheets("Front End").Protect ("29745")
Call timerchoose
Application.ScreenUpdating = True
End Sub
This copies the data from the front page to a raw data sheet every
hour:
Sub transfer()
Sheets("Front End").Unprotect ("29745")
Application.ScreenUpdating = False
Dim x As Long
Dim v As Variant, r As range, rWhere As range
'set starting point at row 8
x = 8
'defines the sheet the data is being coppied from and pasted to
Dim sourceSheet As Worksheet: Set sourceSheet = ThisWorkbook.Worksheets("Front End")
Dim destSheet As Worksheet: Set destSheet = ThisWorkbook.Worksheets("Raw Data")
If sourceSheet.range("I3").Value = "" Then
Call StartTimer
Exit Sub
Else
Do While range("L" & x).Value <> ""
'Checks if the unique code is in the raw data sheet or not
v = sourceSheet.range("M" & x).Value
Set rWhere = destSheet.range("S:S")
Set r = rWhere.Find(what:=v, After:=rWhere(1))
If r Is Nothing Then
'selects the next row where the 1st column is empty
lMaxRows = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row
'pastes the data from the specified cells into the next empty row
destSheet.range("A" & lMaxRows + 1).Value = sourceSheet.range("C2").Value
destSheet.range("M" & lMaxRows + 1).Value = sourceSheet.range("E2").Value
destSheet.range("N" & lMaxRows + 1).Value = sourceSheet.range("E4").Value
destSheet.range("P" & lMaxRows + 1).Value = sourceSheet.range("G4").Value
destSheet.range("Q" & lMaxRows + 1).Value = sourceSheet.range("C4").Value
destSheet.range("O" & lMaxRows + 1).Value = sourceSheet.range("I3").Value
destSheet.range("B" & lMaxRows + 1).Value = sourceSheet.range("J" & x).Value
destSheet.range("C" & lMaxRows + 1).Value = sourceSheet.range("K" & x).Value
destSheet.range("D" & lMaxRows + 1).Value = sourceSheet.range("L" & x).Value
destSheet.range("E" & lMaxRows + 1).Value = sourceSheet.range("I" & x).Value
destSheet.range("S" & lMaxRows + 1).Value = sourceSheet.range("M" & x).Value
x = x + 1
Else
x = x + 1
End If
Loop
x = 8
Do While range("D" & x).Value <> 0
If range("E" & x).Value <> "" Then
'Checks if the unique code is in the raw data sheet or not
v = sourceSheet.range("A" & x).Value
Set rWhere = destSheet.range("S:S")
Set r = rWhere.Find(what:=v, After:=rWhere(1))
If r Is Nothing Then
'selects the next row where the 1st column is empty
lMaxRows = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row
'pastes the data from the specified cells into the next empty row
destSheet.range("A" & lMaxRows + 1).Value = sourceSheet.range("C2").Value
destSheet.range("M" & lMaxRows + 1).Value = sourceSheet.range("E2").Value
destSheet.range("N" & lMaxRows + 1).Value = sourceSheet.range("E4").Value
destSheet.range("P" & lMaxRows + 1).Value = sourceSheet.range("G4").Value
destSheet.range("Q" & lMaxRows + 1).Value = sourceSheet.range("C4").Value
destSheet.range("O" & lMaxRows + 1).Value = sourceSheet.range("I3").Value
destSheet.range("B" & lMaxRows + 1).Value = sourceSheet.range("B" & x).Value
destSheet.range("L" & lMaxRows + 1).Value = sourceSheet.range("C" & x).Value
destSheet.range("F" & lMaxRows + 1).Value = sourceSheet.range("D" & x).Value
destSheet.range("G" & lMaxRows + 1).Value = sourceSheet.range("E" & x).Value
destSheet.range("I" & lMaxRows + 1).Value = sourceSheet.range("G" & x).Value
destSheet.range("K" & lMaxRows + 1).Value = sourceSheet.range("H" & x).Value
destSheet.range("H" & lMaxRows + 1).Value = sourceSheet.range("N" & x).Value
destSheet.range("J" & lMaxRows + 1).Value = sourceSheet.range("O" & x).Value
destSheet.range("S" & lMaxRows + 1).Value = sourceSheet.range("A" & x).Value
x = x + 1
Else
x = x + 1
End If
Else
x = x + 1
End If
Loop
'sorts Raw Data table after new data is added
Dim ws As Worksheet
Set ws = ActiveWorkbook.Worksheets("Raw Data")
'specifies how to sort the data
With ws.Sort.SortFields
.Clear
.add Key:=ws.range("A2:A" & lMaxRows + 1), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
.add Key:=ws.range("B2:B" & lMaxRows + 1), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
'specifies range over which to sort
End With
With ws.Sort
.SetRange ws.range("A1:S" & lMaxRows + 1)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End If
Sheets("Front End").Protect ("29745")
Call SortDTWeek
Call SortDTMonth
Call StartTimer
Application.ScreenUpdating = True
End Sub
This checks a few cells constantly to see if they have been double
clicked, if so it puts the current time in that cell
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As range, cancel As Boolean)
'Adds downtime start and finish values
'Check to see if the click/selected cell is in columns I or J
If Not Intersect(Target, range("J:K")) Is Nothing Then
'Make sure cell is in range
If Target.Row > 7 And Target.Row <= 27 Then
'Update the value
Target.Value = Time()
End If
End If
End Sub
Checks to see if a set of cells has been changed, if so it puts the
now() value in a corresponding "key" column
Private Sub Worksheet_Change(ByVal Target As range)
Sheets("Front End").Unprotect ("29745")
Dim cell As range
'Adds unique keyA values
'Check to see if the changed cell is in column E
If Not Intersect(Target, range("E:E")) Is Nothing Then
For Each cell In Target.Cells
If cell.Value <> vbNullString And Target.Row > 7 And Target.Row <= 20 Then
'Update the "KeyA" value
Sheets("Front End").range("A" & Target.Row).Value = Now()
End If
Next cell
Else
'Adds unique keyB values
'Check to see if the changed cell is in column K
If Not Intersect(Target, range("K:K")) Is Nothing Then
For Each cell In Target.Cells
If cell.Value <> vbNullString And (Target.Row > "6" And Target.Row <= "27") Then
'Update the "KeyM" value
range("M" & Target.Row).Value = Now()
End If
Next cell
End If
End If
Sheets("Front End").Unprotect ("29745")
End Sub
thanks for any input this issue has been driving me crazy
as #MLind suggested in the comments, to bypass the corrupted file error and pull some data out i added this to my code:
Workbooks.Open Filename:=MyPath & MyWB, ReadOnly:=True, IgnoreReadOnlyRecommended:=True,
CorruptLoad:=xlExtractData
and used
Application.DisplayAlerts = False
within the loop to prevent any pop up boxes from stopping the sub

I need a macro that will check new entries if it is already existing or it is within the range of an existing entry

I have 2 files with name NewEntries.CSV and Existing.CSV
Header A1(Company Code), B1(PurchaseOrg),C1(TransactionType),D1(CommodityCode),E1(MinTC),F1(MaxTC)
how will I implement this condition to check the New Entries and copy same or within the range entries in a new file or sheet.
IF [NewEntries(A1,B1,C1,D1) = Existing(A1,B1,C1,D1:A*,B*,C*,D*)] & [NewEntries(E1)>= Existing(E*) OR NewEntries(F1)<= Existing(F*)]
Check your logic first.
Put that code below in a new workbook. (Code may be shorten. To see the logic this is better.)
Private Sub FindNews()
Dim intRowE As Long
Dim intRowN As Long
Dim intRowD As Long
Dim Existing As Workbook
Dim NewEntries As Workbook
Dim WorksheetExisting
Dim WorksheetNewEntries
Application.ScreenUpdating = false
Set Existing = Workbooks.Open(Filename:=Application.ActiveWorkbook.Path & "\Existing.csv")
Set NewEntries = Workbooks.Open(Filename:=Application.ActiveWorkbook.Path & "\NewEntries.csv")
Set WorksheetExisting = Existing.Worksheets("Sheet1")
Set WorksheetNewEntries = NewEntries.Worksheets("Sheet1")
intRowD = 1
For intRowN = 2 To WorksheetNewEntries.UsedRange.Rows.Count
For intRowE = 2 To WorksheetExisting.UsedRange.Rows.Count
If (WorksheetNewEntries.Cells(intRowN, 1).Value = WorksheetExisting.Cells(intRowE, 1).Value _
And WorksheetNewEntries.Cells(intRowN, 2).Value = WorksheetExisting.Cells(intRowE, 2).Value _
And WorksheetNewEntries.Cells(intRowN, 3).Value = WorksheetExisting.Cells(intRowE, 3).Value _
And WorksheetNewEntries.Cells(intRowN, 4).Value = WorksheetExisting.Cells(intRowE, 4).Value) _
And (WorksheetNewEntries.Cells(intRowN, 5).Value >= WorksheetExisting.Cells(intRowE, 5).Value _
Or WorksheetNewEntries.Cells(intRowN, 6).Value <= WorksheetExisting.Cells(intRowE, 6).Value) Then
Range("A" & CStr(intRowD) & ":F" & CStr(intRowD)).Value = WorksheetExisting.Range("A" & CStr(intRowN) & ":F" & CStr(intRowN)).Value
intRowD = intRowD + 1
Exit For
End If
Next
Next
Application.ScreenUpdating = true
Existing.Close SaveChanges:=False
NewEntries.Close SaveChanges:=False
End Sub
#kitap mitap
I have run this code but encountered subscript error in
ActiveWorkbook.Worksheets("sheet1").Cells(intRowD, 1).Value = WorksheetNewEntries.Cells(intRowN, 1).Value
Here is the complete Code:
Sub Button1_Click()
'
' Button1_Click Macro
'
Dim intRowE As Long
Dim intRowN As Long
Dim intRowD As Long
Dim Existing As Workbook
Dim NewEntries As Workbook
Dim WorksheetExisting As Worksheet
Dim WorksheetNewEntries As Worksheet
Dim wb As Workbook
Dim strFile As String, strDir As String
strDir = "C:\Users\john.michael.a.bunyi\Desktop\FR044 Testing\"
strFile = Dir(strDir & "Acc_FR044_SAP.csv")
Do While strFile <> ""
Set wb = Workbooks.Open(Filename:=strDir & strFile, Local:=True)
wb.SaveAs Replace(wb.FullName, ".csv", ".xls"), FileFormat:=xlExcel8
wb.Close True
Set wb = Nothing
strFile = Dir
Loop
strDir = "C:\Users\john.michael.a.bunyi\Desktop\FR044 Testing\"
strFile = Dir(strDir & "Acc_FR044_SAP - New Entries.csv")
Do While strFile <> ""
Set wb = Workbooks.Open(Filename:=strDir & strFile, Local:=True)
wb.SaveAs Replace(wb.FullName, ".csv", ".xls"), FileFormat:=xlExcel8
wb.Close True
Set wb = Nothing
strFile = Dir
Loop
Set Existing = Workbooks.Open(Filename:="C:\Users\john.michael.a.bunyi\Desktop\FR044 Testing\Acc_FR044_SAP.xls")
Set NewEntries = Workbooks.Open(Filename:="C:\Users\john.michael.a.bunyi\Desktop\FR044 Testing\Acc_FR044_SAP - New Entries.xls")
Set WorksheetExisting = Existing.Worksheets("Acc_FR044_SAP")
Set WorksheetNewEntries = NewEntries.Worksheets("Acc_FR044_SAP - New Entries")
intRowD = 1
For intRowN = 2 To WorksheetNewEntries.UsedRange.Rows.Count
For intRowE = 2 To WorksheetExisting.UsedRange.Rows.Count
If (WorksheetNewEntries.Cells(intRowN, 1).Value = WorksheetExisting.Cells(intRowE, 1).Value _
And WorksheetNewEntries.Cells(intRowN, 2).Value = WorksheetExisting.Cells(intRowE, 2).Value _
And WorksheetNewEntries.Cells(intRowN, 3).Value = WorksheetExisting.Cells(intRowE, 3).Value _
And WorksheetNewEntries.Cells(intRowN, 4).Value = WorksheetExisting.Cells(intRowE, 4).Value) _
And (WorksheetNewEntries.Cells(intRowN, 5).Value >= WorksheetExisting.Cells(intRowE, 5).Value _
Or WorksheetNewEntries.Cells(intRowN, 6).Value <= WorksheetExisting.Cells(intRowE, 6).Value) Then
ActiveWorkbook.Worksheets("sheet1").Cells(intRowD, 1).Value = WorksheetNewEntries.Cells(intRowN, 1).Value
ActiveWorkbook.Worksheets("sheet1").Cells(intRowD, 2).Value = WorksheetNewEntries.Cells(intRowN, 2).Value
ActiveWorkbook.Worksheets("sheet1").Cells(intRowD, 3).Value = WorksheetNewEntries.Cells(intRowN, 3).Value
ActiveWorkbook.Worksheets("sheet1").Cells(intRowD, 4).Value = WorksheetNewEntries.Cells(intRowN, 4).Value
ActiveWorkbook.Worksheets("sheet1").Cells(intRowD, 5).Value = WorksheetNewEntries.Cells(intRowN, 5).Value
ActiveWorkbook.Worksheets("sheet1").Cells(intRowD, 6).Value = WorksheetNewEntries.Cells(intRowN, 6).Value
intRowD = intRowD + 1
End If
Next
Next
Workbooks("Acc_FR044_SAP.xls").Close
Workbooks("Acc_FR044_SAP - New Entries.xls").Close
End Sub