VBA change cell value to run another macro - vba

I hope you can help.
I have a lengthy piece of code, CODE 2 what this does is it allows a user to open a dialog box, select a sheet, once a sheet is selected it formats the sheet, filters the 7th column then adds new sheets with copied information from 7th column, names the sheets, formats again, adds and deletes columns, subtracts dates and returns numbers, and I essentially end up with what you see in Pic 1 (more happens but that is the gist of it) I am happy with CODE 2
I also have CODE 1 now with this if a user selects a value in A2 that is not "Enter Your Country Here" then all the "Enter Your Country Here" in the workbook get replaced with the new value in A2.
CODE 1 also works fine
The problem is i cant seem to join CODE 1 into CODE 2. CODE 1 works perfectly by itself but I cant seem to call it or get it to fire where ever I place or call it in CODE 2
Can CODE 1 be worked into CODE 2 so that when a user selects a country it finds and replaces "Enter Your Country Here" with the selected value in A2
Like a said both codes work fine separately I just need to bring 1 into 2 some how
As always any and all help is greatly appreciated.
Pic 1
CODE 1
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("A2")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
' Display a message when one of the designated cells has been
' changed.
' Place your code here.
Call Find_Replace
End If
End Sub
Public Sub Find_Replace()
Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant
fnd = "Enter Your Country Here"
rplc = Worksheets("SearchCasesResults").Range("A2").Value
For Each sht In ActiveWorkbook.Worksheets
sht.Cells.Replace what:=fnd, Replacement:=rplc, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next sht
End Sub
CODE 2
Sub Open_Workbook_Dialog()
Dim my_FileName As Variant
MsgBox "Pick your Disputes file" '<--| txt box for prompt to pick a file
my_FileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*") '<--| Opens the file window to allow selection
If my_FileName <> False Then
Workbooks.Open Filename:=my_FileName
Call Sort_Disputes '<--|Calls Sort Disputes and begins to format
End If
End Sub
Public Sub Sort_Disputes()
With ActiveWorkbook.Sheets(1)
Rows("1:5").Delete '<--|Deletes the first 5 rows
Range("A1").EntireColumn.Insert '<--|Inserts a new A column
Range("A1").Value = "Market" '<--|Market text enters cell A1
Cells(1, 2).Copy
Cells(1, 1).PasteSpecial (xlPasteFormats) '<--|Keeps the formatting of other columns and forces to new column A
Application.CutCopyMode = False
Columns.AutoFit '<--|Auto fits the columns
Range("C:C,J:J,M:AF").EntireColumn.Delete '<--|Deletes Columns
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
Call populateA '<--|Calls PopulateA and this takes a look a Column A and where blank enters text
End With
Call Filter '<--|Calls Filter which looks down the 7th Column and seperates out the sheets to new tabs based on the value in Column 7
Call Activate_Sheet '<--|Deletes a column then subtracts todays date from the date in C and represents as a number in D
Call Activate_Sheet_2 '<--|As long as C is not blank it will subtract the Date in C from the Date in D and return a numerical result
Call Add_Sheet
End Sub
Public Sub Filter()
Dim rCountry As Range, helpCol As Range
With ActiveWorkbook.Sheets(1) '<--| refer to data worksheet
With .UsedRange
Set helpCol = .Resize(1, 1).Offset(, .Columns.Count) '<--| get a "helper" column just at the right of used range, it'll be used to store unique country names in
End With
With .Range("A1:Q" & .Cells(.Rows.Count, 1).End(xlUp).Row) '<--| refer to its columns "A:Q" from row 1 to last non empty row of column "A"
.Columns(7).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=helpCol, Unique:=True '<-- call AdvancedFilter on 7th column of the referenced range and store its unique values in "helper" column
Set helpCol = Range(helpCol.Offset(1), helpCol.End(xlDown)) '<--| set range with unique names in (skip header row)
For Each rCountry In helpCol '<--| iterate over unique country names range (skip header row)
.AutoFilter 7, rCountry.Value2 '<--| filter data on country field (7th column) with current unique country name
If Application.WorksheetFunction.Subtotal(103, .Cells.Resize(, 1)) > 1 Then '<--| if any cell other than header ones has been filtered...
Worksheets.Add Worksheets(Worksheets.Count) '<--... add new sheet
ActiveSheet.Name = rCountry.Value2 '<--... rename it
.SpecialCells(xlCellTypeVisible).Copy ActiveSheet.Range("A1") 'copy data for country under header
End If
Next
End With
.AutoFilterMode = False '<--| remove autofilter and show all rows back
End With
helpCol.Offset(-1).End(xlDown).EntireColumn.Delete '<--| clear helper column (header included)
End Sub
Public Sub populateA()
Dim WS As Worksheet
Dim lRow As Long
Set WS = ActiveWorkbook.Sheets(1)
With WS
lRow = .Range("B" & .Rows.Count).End(xlUp).Row '<--| Looks for the last empty cell in Column B
.Range("A2:A" & lRow).Formula = "=If(B2<>"""",""Enter Your Country Here"","""")" '<--| If there is no blank cell in B and A has a blank cell then A gets populated with "Enter your Country Here"
.Range("A2:A" & lRow).Value = .Range("A2:A" & lRow).Value
.Range("A2:A" & lRow).Interior.ColorIndex = 39 '<--|Changes the colour of A
End With
End Sub
Public Sub Activate_Sheet()
Worksheets("In Progress").Activate '<--|Activates Inprogress Sheet
Columns.AutoFit '<--|Auto fits Columns
Range("N:N").EntireColumn.Delete '<--|Delete Columns
Range("D1").Value = "# days open" '<--|Enters Value
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
Dim LastRow As Long, i As Long
With Worksheets("In Progress")
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row '<--|Looks for the last non empty cell in C
For i = 2 To LastRow
.Range("D" & i).Value = DateDiff("d", .Range("C" & i).Value, Date) '<--|As long as C is not blank it will subtract todays date from C and populate in D
Next i
End With
End Sub
Public Sub Activate_Sheet_2()
Worksheets("Complete").Activate '<--|Activates Complete Sheet
Columns.AutoFit '<--|Auto fits Columns
Range("N:N").EntireColumn.Delete '<--|Deletes Columns
Range("E1").EntireColumn.Insert '<--|Inserts Columns
Range("E1").Value = "Overall Ticket Aging" '<--|Enters Value
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
Dim LastRow As Long, i As Long
With Worksheets("Complete")
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
For i = 2 To LastRow
.Range("E" & i).Value = DateDiff("d", .Range("C" & i).Value, .Range("D" & i).Value) '<--|As long as C is not blank it will subtract the Date in C from the Date in D and return a numerical result
Next i
End With
Columns(5).NumberFormat = "0" '<--|Formats the 5 column to number format
End Sub
Public Sub Add_Sheet()
''Dim WS As Worksheet
''Set WS = Sheets.Add
Sheets.Add.Name = "Countries"
Worksheets("Countries").Activate
Range("A1").Value = "Country"
Range("A2").Value = "UK"
Range("A3").Value = "Belgium"
Range("A4").Value = "Bulgaria"
Range("A5").Value = "Croatia"
Range("A6").Value = "Czech Republic"
Range("A7").Value = "Slovenia"
Range("A8").Value = "Spain"
Range("A9").Value = "Italy"
Range("A10").Value = "Germany"
Worksheets("SearchCasesResults").Activate
Call Auto_Filter
End Sub
Public Sub Auto_Filter()
'replace "J2" with the cell you want to insert the drop down list
With Range("A2").Validation
.Delete
'replace "=A2:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=Countries!A2:A10"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
To solve this I needed VBA code that would put Change Event VBA code into another worksheet. Calling the code I had was not working as I was calling a Change Event which didn't make sense. I needed code to put the change event into the sheet.
The code I used to put the change event into the the sheet in my example in the pic the sheet named "SearchCasesResults" is below I hope it helps someone.
CODE to put code into another sheet
Public Sub CreateEventProcedure()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim LineNum As Long
Const DQUOTE = """" ' one " character
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("Sheet1")
Set CodeMod = VBComp.CodeModule
With CodeMod
LineNum = .CreateEventProc("Change", "Worksheet")
LineNum = LineNum + 1
''.InsertLines LineNum, " MsgBox " & DQUOTE & "Hello World" & DQUOTE
''.InsertLines LineNum, " Cells.Columns.AutoFit"
''.InsertLines LineNum, " End Sub"
.InsertLines LineNum, " Worksheets(" & DQUOTE & "SearchCasesResults" & DQUOTE & ").Activate"
.InsertLines LineNum, " Next sht"
.InsertLines LineNum, " SearchFormat:=False, ReplaceFormat:=False"
.InsertLines LineNum, " LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _"
.InsertLines LineNum, " sht.Cells.Replace what:=fnd, Replacement:=rplc, _"
.InsertLines LineNum, " For Each sht In ActiveWorkbook.Worksheets"
.InsertLines LineNum, " rplc = Worksheets(" & DQUOTE & "SearchCasesResults" & DQUOTE & ").Range(" & DQUOTE & "A2" & DQUOTE & ").Value"
.InsertLines LineNum, " fnd = " & DQUOTE & "Enter Your Country Here" & DQUOTE & ""
.InsertLines LineNum, " Dim rplc As Variant"
.InsertLines LineNum, " Dim fnd As Variant"
.InsertLines LineNum, " Dim sht As Worksheet"
End With
End Sub

Related

Excel VBA - Copy and Paste Loop in VBA based on cell value

I am trying to come up with a macro that checks if any numeral value exists in a cell. If a numeral value exists, copy a portion of that row and paste it into another worksheet within the same spreadsheet.
Sheet1 is the sheet that has all my data in it. I am trying to look in column R if there is any values in it. If it does, copy that cell and the four adjacent cells to the left of it and paste it into Sheet2.
This is what I have come up with so far based on mish-mashing other people's code though it only does a part of what I want. It just copies part of a row then pastes it into another worksheet but it does not check column R for a value first. It just copies and pastes regardless and does not move onto the next row once it has done that. I need it to continue onto the next row to continue looking:
Sub Paste_Value_Test()
Dim c As Range
Dim IRow As Long, lastrow As Long
Dim rSource As Range
Dim wsI As Worksheet, wsO As Worksheet
On Error GoTo Whoa
'~~> Sheet Where values needs to be checked
Set wsI = ThisWorkbook.Sheets("Sheet1")
'~~> Output sheet
Set wsO = ThisWorkbook.Sheets("Sheet2")
Application.ScreenUpdating = False
With wsI
'~~> Find Last Row which has data in Col O to R
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Columns("O:R").Find(What:="*", _
After:=.Range("O3"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If
'~~> Set you input range
Set rSource = .Range("R" & lastrow)
'~~> Search for the cell which has "L" and then copy it across to sheet1
For Each c In rSource
Debug.Print cValue
If c.Value > "0" Then
.Range("O" & c.Row & ":R" & c.Row).Copy
wsO.Cells(5 + IRow, 12).PasteSpecial Paste:=xlPasteValues
IRow = IRow + 1
End If
Next
End With
LetsContinue:
Application.ScreenUpdating = True
Application.CutCopyMode = False
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
Below is some code which hopefully achieves what I think you are trying to do. I have included comments throughout stating what I changed:
Sub Paste_Value_Test()
Dim c As Range
Dim IRow As Long, lastrow As Long
Dim rSource As Range
Dim wsI As Worksheet, wsO As Worksheet
On Error GoTo Whoa
'~~> Sheet Where values needs to be checked
Set wsI = ThisWorkbook.Sheets("Sheet1")
'~~> Output sheet
Set wsO = ThisWorkbook.Sheets("Sheet2")
Application.ScreenUpdating = False
With wsI
'~~> Find Last Row which has data in Col O to R
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
'You specified "After" to be cell O3. This means a match will
' occur on row 2 if cell R2 (or O2 or P2) has something in it
' because cell R2 is the cell "after" O3 when
' "SearchDirection:=xlPrevious"
' After:=.Range("O3"), _
lastrow = .Columns("O:R").Find(What:="*", _
After:=.Range("O1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If
'This was only referring to the single cell in column R on the
' last row (in columns O:R)
'Set rSource = .Range("R" & lastrow)
'Create a range referring to everything in column R, from row 1
' down to the "last row"
Set rSource = .Range("R1:R" & lastrow)
'This comment doesn't seem to reflect what the code was doing, or what the
'question said
'~~> Search for the cell which has "L" and then copy it across to sheet1
For Each c In rSource
'This is printing the variable "cValue", which has never been set
'Debug.Print cValue
'It was probably meant to be
Debug.Print c.Value
'This was testing whether the value in the cell was
' greater than the string "0"
'So the following values would be > "0"
' ABC
' 54
' ;asd
'And the following values would not be > "0"
' (ABC)
' $523 (assuming that was as text, and not just 523 formatted as currency)
'If c.Value > "0" Then
'I suspect you are trying to test whether the cell is numeric
' and greater than 0
If IsNumeric(c.Value) Then
If c.Value > 0 Then
'This is only copying the cell and the *three* cells
' to the left of it
'.Range("O" & c.Row & ":R" & c.Row).Copy
'This will copy the cell and the *four* cells
' to the left of it
'.Range("N" & c.Row & ":R" & c.Row).Copy
'wsO.Cells(5 + IRow, 12).PasteSpecial Paste:=xlPasteValues
'But this would avoid the use of copy/paste
wsO.Cells(5 + IRow, 12).Resize(1, 5).Value = _
.Range("N" & c.Row & ":R" & c.Row).Value
IRow = IRow + 1
End If
End If
Next
End With
LetsContinue:
Application.ScreenUpdating = True
Application.CutCopyMode = False
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub

Excel matching based on name date and copying data to another sheet

I have searched high and low and have tested many VB scripts but havent found a solution to this. the below is the data I have
Data
Need to have an output like below
result
the VB code I am using
Option Explicit
Public Sub PromptUserForInputDates()
Dim strStart As String, strEnd As String, strPromptMessage As String
'Prompt the user to input the start date
strStart = InputBox("Please enter the start date")
'Validate the input string
If Not IsDate(strStart) Then
strPromptMessage = "Oops! It looks like your entry is not a valid " & _
"date. Please retry with a valid date..."
MsgBox strPromptMessage
Exit Sub
End If
'Prompt the user to input the end date
strEnd = InputBox("Please enter the end date")
'Validate the input string
If Not IsDate(strStart) Then
strPromptMessage = "Oops! It looks like your entry is not a valid " & _
"date. Please retry with a valid date..."
MsgBox strPromptMessage
Exit Sub
End If
'Call the next subroutine, which will do produce the output workbook
Call CreateSubsetWorkbook(strStart, strEnd)
End Sub
'This subroutine creates the new workbook based on input from the prompts
Public Sub CreateSubsetWorkbook(StartDate As String, EndDate As String)
Dim wbkOutput As Workbook
Dim wksOutput As Worksheet, wks As Worksheet
Dim lngLastRow As Long, lngLastCol As Long, lngDateCol As Long
Dim rngFull As Range, rngResult As Range, rngTarget As Range
'Set references up-front
lngDateCol = 3 '<~ we know dates are in column C
Set wbkOutput = Workbooks.Add
'Loop through each worksheet
For Each wks In ThisWorkbook.Worksheets
With wks
'Create a new worksheet in the output workbook
Set wksOutput = wbkOutput.Sheets.Add
wksOutput.Name = wks.Name
'Create a destination range on the new worksheet that we
'will copy our filtered data to
Set rngTarget = wksOutput.Cells(1, 1)
'Identify the data range on this sheet for the autofilter step
'by finding the last row and the last column
lngLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
lngLastCol = .Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
Set rngFull = .Range(.Cells(1, 1), .Cells(lngLastRow, lngLastCol))
'Apply a filter to the full range to get only rows that
'are in between the input dates
With rngFull
.AutoFilter Field:=lngDateCol, _
Criteria1:=">=" & StartDate, _
Criteria2:="<=" & EndDate
'Copy only the visible cells and paste to the
'new worksheet in our output workbook
Set rngResult = rngFull.SpecialCells(xlCellTypeVisible)
rngResult.Copy Destination:=rngTarget
End With
'Clear the autofilter safely
.AutoFilterMode = False
If .FilterMode = True Then
.ShowAllData
End If
End With
Next wks
'Let the user know our macro has finished!
MsgBox "Data transferred!"
End Sub
but when data is like below the result doesnt show two rows with different time, any help would be much appreciated please.
Data 3
rgds
thanks for sharing your code. I think it looks a bit more than what you need. Going off your example, if everything is formatted as such, this would be your solution:
Option Explicit
Sub SplitDateTime()
Dim mydate As String, mytime As String, mytime2 As String, i As Long, sht As Worksheet, lastrow As Long
Set sht = ThisWorkbook.Worksheets("Sheet1")
lastrow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
'Change headers
Range("H1:H" & lastrow).Value = Range("G1:G" & lastrow).Value
Range("G1:G" & lastrow).Value = Range("F1:F" & lastrow).Value
Range("D1").Value = "Date"
Range("E1").Value = "C/In"
Range("F1").Value = "C/Out"
'Move values around
For i = 2 To lastrow Step 2
mydate = DateValue(Range("D" & i).Value)
mytime = TimeValue(Range("D" & i).Value)
mytime2 = TimeValue(Range("D" & i + 1).Value)
Range("D" & i).Value = mydate
Range("E" & i).Value = mytime
Range("F" & i).Value = mytime2
Next i
'Delete excess rows
For i = lastrow To 2 Step -2
Range("A" & i).EntireRow.Delete
Next i
'Regrab lastrow value
lastrow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
'Change date format
Range("D2:D" & lastrow).NumberFormat = "m/d/yyyy"
End Sub

Excel VBA: CTRL + F as a macro

This code searches data on Sheet2 and if it finds it on Sheet2,
it copies full row on Sheet1.
I would like to edit it:
so when I search for example "John%Wayne"
it looks for cells that contain and John and Wayne in its string.
Sub myFind()
'Standard module code, like: Module1.
'Find my data and list found rows in report!
Dim rngData As Object
Dim strDataShtNm$, strReportShtNm$, strMySearch$, strMyCell$
Dim lngLstDatCol&, lngLstDatRow&, lngReportLstRow&, lngMyFoundCnt&
On Error GoTo myEnd
'*******************************************************************************
strDataShtNm = "Sheet2" 'This is the name of the sheet that has the data!
strReportShtNm = "Sheet1" 'This is the name of the report to sheet!
'*******************************************************************************
Sheets(strReportShtNm).Select
Application.ScreenUpdating = False
'Define data sheet's data range!
Sheets(strDataShtNm).Select
With ActiveSheet.UsedRange
lngLstDatRow = .Rows.Count + .Row - 1
lngLstDatCol = .Columns.Count + .Column - 1
End With
Set rngData = ActiveSheet.Range(Cells(1, 1), Cells(lngLstDatRow, lngLstDatCol))
'Get the string to search for!
strMySearch = InputBox("Enter what to search for, below:" & vbLf & vbLf & _
"Note: The search is case sensitive!", _
Space(3) & "Find All", _
"")
'Do the search!
For Each Cell In rngData
strMyCell = Cell.Value
'If found then list entire row!
If strMyCell = strMySearch Then
lngMyFoundCnt = lngMyFoundCnt + 1
ActiveSheet.Rows(Cell.Row & ":" & Cell.Row).Copy
With Sheets(strReportShtNm)
'Paste found data's row!
lngReportLstRow = .UsedRange.Rows.Count + .UsedRange.Row
ActiveSheet.Paste Destination:=.Range("A" & lngReportLstRow).EntireRow
End With
End If
Next Cell
myEnd:
'Do clean-up!
Application.ScreenUpdating = True
Application.CutCopyMode = False
Sheets(strReportShtNm).Select
'If not found then notify!
If lngMyFoundCnt = 0 Then
MsgBox """" & strMySearch & """" & Space(3) & "Was not found!", _
vbCritical + vbOKOnly, _
Space(3) & "Not Found!"
End If
End Sub
You can use Find with the * wildcard (or if you really want to use % then replace % with * in the code):
Sub myFind()
Dim rToSearch As Range
Dim sMySearch As String
Dim rFound As Range
Dim sFirstAddress As String
Dim lLastRow As Long
'Get the string to search for!
sMySearch = InputBox("Enter what to search for, below:" & vbLf & vbLf & _
"Note: The search is case sensitive!", _
Space(3) & "Find All", _
"")
With ThisWorkbook
'Set reference to data in column A.
With .Worksheets("Sheet2")
Set rToSearch = .Range(.Cells(1, 1), .Columns(1).Find("*", , , , xlByColumns, xlPrevious))
End With
'Find the last row containing data in Sheet 1.
With .Worksheets("Sheet1")
On Error Resume Next
lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row + 1
On Error GoTo 0
If lLastRow = 0 Then lLastRow = 1
End With
End With
'Use find to search your text.
'FindNext will, strangely enough, find the next occurrence and keep looping until it
'reaches the top again - and back to the first found address.
With rToSearch
Set rFound = .Find(What:=sMySearch, LookIn:=xlValues)
If Not rFound Is Nothing Then
sFirstAddress = rFound.Address
Do
rFound.EntireRow.Copy Destination:=ThisWorkbook.Worksheets("Sheet1").Cells(lLastRow, 1)
lLastRow = lLastRow + 1
Set rFound = .FindNext(rFound)
Loop While rFound.Address <> sFirstAddress
End If
End With
End Sub

Run time error 424. VBA if worksheet is called "In Progress" then execute code Else Msg Box

I hope you can help. I have a piece of code and what it does is it allows a user to open a dialog box then select an excel file. This selected excel file then gets formatted, it then puts a filter on the 8th column it then creates new excel sheets copies and pastes the information to these sheets and names the new sheet based on the data in the 8th column.
So I end up with an excel workbook like the one you see in Pic 1
As you can see in PIC 1 I have the original sheet "Searchcaseresults" and the sheets "In Progress" and "Complete"
What I am trying to achieve is code that goes if in this workbook there is a sheet called "In Progress" then execute code on that sheet if there is not a sheet called "in Progress then Msg Box "no In progress sheet found" or do nothing and if there is a sheet in this workbook called "Complete" then execute code and if there is no sheet called Complete in this workbook then Msg Box "no complete sheet found" or do nothing.
At the moment I have not entered the Complete code because I getting Run time error 424 on line If Worksheet.Name = "In Progress" Then and I would like to solve this first.
The area of code that is giving me trouble is here
''''Trouble code
Dim wb As Workbook
With wb
If Worksheet.Name = "In Progress" Then
Columns.AutoFit '<--|Auto fits Columns
Range("E1").Value = "# days open" '<--|Enters Value
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
Dim LastRow As Long, i As Long
With Worksheets("In Progress")
LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row '<--|Looks for the last non empty cell in C
For i = 2 To LastRow
.Range("E" & i).Value = DateDiff("d", .Range("D" & i).Value, Date) '<--|As long as C is not blank it will subtract todays date from C and populate in D
Next i
End With
Else
MsgBox "In Progress Sheet not Found"
End If
End With
and my code in its entirety is below PIC 1
As always any and all help is greatly appreciated.
PIC 1
TOTAL CODE
Sub Open_Workbook_Dialog()
Dim my_FileName As Variant
MsgBox "Pick your TOV file" '<--| txt box for prompt to pick a file
my_FileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*") '<--| Opens the file window to allow selection
If my_FileName <> False Then
Workbooks.Open Filename:=my_FileName
Call Sample '<--|Calls the sample Code and executes
End If
End Sub
Public Sub Sample()
Dim ws As Worksheet
Dim aCell As Range, Rng As Range
Dim col As Long, lRow As Long
Dim colName As String
Set ws = ActiveWorkbook.Sheets(1)
With ws
Rows("1:5").Delete
End With
With ws
Set aCell = .Range("A1:AH50").Find(What:="Issue No", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
'~~> If Found
If Not aCell Is Nothing Then
'~~> Cut the entire column
aCell.EntireColumn.Cut
'~~> Insert the column here
Columns("A:A").Insert Shift:=xlToRight
Else
MsgBox "Country Not Found"
End If
End With
With ws
Set aCell = .Range("A1:AH50").Find(What:="NPI Number", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
'~~> If Found
If Not aCell Is Nothing Then
'~~> Cut the entire column
aCell.EntireColumn.Cut
'~~> Insert the column here
Columns("J:J").Insert Shift:=xlToRight
Else
MsgBox "Country Not Found"
End If
End With
With ws
Range("A1").EntireColumn.Insert
Range("A1").Value = "Market"
Cells(1, 2).Copy
Cells(1, 1).PasteSpecial (xlPasteFormats)
Application.CutCopyMode = False
Columns.AutoFit
Range("O:AH").EntireColumn.Delete
Rows("2:2500").RowHeight = 25
End With
With ws
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
.Range("A2:A" & lRow).Formula = "=If(B2<>"""",""Enter Your Country Here"","""")"
.Range("A2:A" & lRow).Value = .Range("A2:A" & lRow).Value
.Range("A2:A" & lRow).Interior.ColorIndex = 39
End With
Dim rCountry As Range, helpCol As Range
With ws '<--| refer to data worksheet
With .UsedRange
Set helpCol = .Resize(1, 1).Offset(, .Columns.Count) '<--| get a "helper" column just at the right of used range, it'll be used to store unique country names in
End With
With .Range("A1:Q" & .Cells(.Rows.Count, 1).End(xlUp).Row) '<--| refer to its columns "A:Q" from row 1 to last non empty row of column "A"
.Columns(8).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=helpCol, Unique:=True '<-- call AdvancedFilter on 7th column of the referenced range and store its unique values in "helper" column
Set helpCol = Range(helpCol.Offset(1), helpCol.End(xlDown)) '<--| set range with unique names in (skip header row)
For Each rCountry In helpCol '<--| iterate over unique country names range (skip header row)
.AutoFilter 8, rCountry.Value2 '<--| filter data on country field (7th column) with current unique country name
If Application.WorksheetFunction.Subtotal(103, .Cells.Resize(, 1)) > 1 Then '<--| if any cell other than header ones has been filtered...
Worksheets.Add Worksheets(Worksheets.Count) '<--... add new sheet
ActiveSheet.Name = rCountry.Value2 '<--... rename it
.SpecialCells(xlCellTypeVisible).Copy ActiveSheet.Range("A1") 'copy data for country under header
End If
Next
End With
.AutoFilterMode = False '<--| remove autofilter and show all rows back
End With
helpCol.Offset(-1).End(xlDown).EntireColumn.Delete '<--| clear helper column (header included)
''''Trouble code
Dim wb As Workbook
With wb
If Worksheet.Name = "In Progress" Then
Columns.AutoFit '<--|Auto fits Columns
Range("E1").Value = "# days open" '<--|Enters Value
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
Dim LastRow As Long, i As Long
With Worksheets("In Progress")
LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row '<--|Looks for the last non empty cell in C
For i = 2 To LastRow
.Range("E" & i).Value = DateDiff("d", .Range("D" & i).Value, Date) '<--|As long as C is not blank it will subtract todays date from C and populate in D
Next i
End With
Else
MsgBox "In Progress Sheet not Found"
End If
End With
End Sub
I have simplified the code but I am still getting an error the error I am now getting is run-time error 91
The run-time error 91 is happening on line If worksheet.name = "In Progress" Then
The code I am trying to get to work is below
Public Sub Msg_Box()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim worksheet As worksheet
With wb
If worksheet.name = "In Progress" Then
MsgBox "found"
Else
MsgBox "not found"
End If
End With
End Sub
Private Function SheetExists(ByVal SheetName as String, ByRef InWorkbook As Workbook) As Boolean
On Error Resume Next
Debug.Print InWorkbook.Worksheets(SheetName).Name
If Err.Number = 0 Then SheetExists = True Else SheetExists = False
End Function
Use this function to test if the workbook opened has a sheet named "In Progress". For example:
If SheetExists("In Progress", wb) Then
'Some code to execute
Else
MsgBox "No In Progress sheet found"
End If
So what i think was happening is that I was not activating the the sheet name "In Progress"
The code that finally worked for me is below. Again I would to thank all those who assisted, and I hope this helps another Excel enthusiast with a solution
'''''Trouble code
Dim wb As Workbook
''Dim ws As Worksheet <-- this was dotted out as it is declared earlier in the code
Set wb = ActiveWorkbook
For Each ws In wb.Worksheets
If ws.Name = "In Progress" Then
Worksheets("In Progress").Activate ''<-- this what I believe need to happen activate the sheet
Columns.AutoFit '<--|Auto fits Columns
Range("E1").Value = "# days open" '<--|Enters Value
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
With Worksheets("In Progress")
LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row '<--|Looks for the last non empty cell in C
For i = 2 To LastRow
.Range("E" & i).Value = DateDiff("d", .Range("D" & i).Value, Date) '<--|As long as C is not blank it will subtract todays date from C and populate in D
Next i
End With
Columns(5).NumberFormat = "0"
Range("P:P").EntireColumn.Delete
End If
Next

Copying Selective Rows from Sheet1 to Sheet2

Hi all I need to selectively copy entire rows from sheet1 to other sheet. As of now I am using checkboxes to select the rows and then copy the selected rows to sheet of user's choice. But I am facing a bizarre error. For sometime the code runs fine, copying exact data to sheets but after some time it copies erroneous values from nowhere. Can you please help me with this? Pasting the code I am using.
Sub Addcheckboxes()
Dim cell, LRow As Single
Dim chkbx As CheckBox
Dim MyLeft, MyTop, MyHeight, MyWidth As Double
Application.ScreenUpdating = False
LRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
For cell = 2 To LRow
If Cells(cell, "A").Value <> "" Then
MyLeft = Cells(cell, "E").Left
MyTop = Cells(cell, "E").Top
MyHeight = Cells(cell, "E").Height
MyWidth = Cells(cell, "E").Width
ActiveSheet.CheckBoxes.Add(MyLeft, MyTop, MyWidth, MyHeight).Select
With Selection
.Caption = ""
.Value = xlOff
.Display3DShading = False
End With
End If
Next cell
Application.ScreenUpdating = True
End Sub
Sub RemoveCheckboxes()
Dim chkbx As CheckBox
For Each chkbx In ActiveSheet.CheckBoxes
chkbx.Delete
Next
End Sub
Sub CopyRows()
Dim Val As String
Val = InputBox(Prompt:="Sheet name please.", _
Title:="ENTER SHEET NAME", Default:="Sheet Name here")
For Each chkbx In ActiveSheet.CheckBoxes
If chkbx.Value = 1 Then
For r = 1 To Rows.Count
If Cells(r, 1).Top = chkbx.Top Then
With Worksheets(Val)
LRow = .Range("A" & Rows.Count).End(xlUp).Row + 1
.Range("A" & LRow & ":AF" & LRow) = _
Worksheets("Usable_Inv_Data").Range("A" & r & ":AF" & r).Value
End With
Exit For
End If
Next r
End If
Next
End Sub
Normal Copy Output:
Erroneous Copy Output for same values:
Doing a quick comparison of the normal and the erroneous outputs, it looks like some of your cells/columns are not formatted correctly in your destination sheet (where you are "pasting" the values).
For example, your Base Change column in the Normal copy (the value 582.16) is formatted as a General or Number. The same column in the destination sheet is formatted as a date (582.16 converted to a date value in Excel will be 8/4/1901, or 8/4/01, as shown in your screen.
Just make sure the columns are formatted to display the data type you expect. On your destination sheet, select the column, right-click "Format Cells", and then select the appropriate data type.
---EDIT---
To automate the formatting, you would have to copy and paste the values, inclusive of the formats. Your code would change from this:
With Worksheets(Val)
LRow = .Range("A" & Rows.Count).End(xlUp).Row + 1
.Range("A" & LRow & ":AF" & LRow) = _
Worksheets("Usable_Inv_Data").Range("A" & r & ":AF" & r).Value
End With
TO
With Worksheets(Val)
LRow = .Range("A" & Rows.Count).End(xlUp).Row + 1
Worksheets("Usable_Inv_Data").Range("A" & r & ":AF" & r).Copy
.Range("A" & LRow).PasteSpecial (xlPasteValuesAndNumberFormats)
End With
I have added the checkbox with LinkedCell property. This helps to identify the rows when checkbox is checked.
Also i have added a function check_worksheet_exists which will check if the workbook exist.
Sub Addcheckboxes()
Dim cell, LRow As Single
Dim chkbx As CheckBox
Dim MyLeft, MyTop, MyHeight, MyWidth As Double
Application.ScreenUpdating = False
LRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).row
For cell = 2 To LRow
If Cells(cell, "A").Value <> "" Then
MyLeft = Cells(cell, "E").Left
MyTop = Cells(cell, "E").Top
MyHeight = Cells(cell, "E").Height
MyWidth = Cells(cell, "E").Width
ActiveSheet.CheckBoxes.Add(MyLeft, MyTop, MyWidth, MyHeight).Select
With Selection
.Caption = ""
.Value = xlOff
.Display3DShading = False
.LinkedCell = Cells(cell, "AZ").Address
End With
End If
Next cell
Application.ScreenUpdating = True
End Sub
Sub RemoveCheckboxes()
Dim chkbx As CheckBox
For Each chkbx In ActiveSheet.CheckBoxes
chkbx.Delete
Next
End Sub
Sub CopyRows()
Dim Val As String
Dim row As Long
Val = InputBox(Prompt:="Sheet name please.", Title:="ENTER SHEET NAME", Default:="Sheet Name here")
If check_worksheet_exists(ThisWorkbook, Val, False) = False Then
Exit Sub
End If
For Each chkbx In ActiveSheet.CheckBoxes
If chkbx.Value = 1 Then
row = Range(chkbx.LinkedCell).row
With Worksheets(Val)
LRow = .Range("A" & Rows.Count).End(xlUp).row + 1
.Range("A" & LRow & ":AF" & LRow) = ActiveSheet.Range("A" & row & ":AF" & row).Value
End With
End If
Next
End Sub
Function check_worksheet_exists(tBook As Workbook, ByVal check_sheet As String, Optional no_warning As Boolean = False) As Boolean
On Error Resume Next
Dim wkSht As Worksheet
Set wkSht = tBook.Sheets(check_sheet)
If Not wkSht Is Nothing Then
check_worksheet_exists = True
ElseIf wkSht Is Nothing And no_warning = False Then
MsgBox "'" & check_sheet & "' sheet does not exist", vbCritical, "Error"
End If
On Error GoTo 0
End Function
i cannot immediately see the errors you refer to, unless you are referring to the sequences of hash-signs ###? These just indicate that the columns aren't wide enough.
Worksheets(Val).Range("A1").CurrentRegion.EntireColumn.AutoFit
BTW I don't think Val is a sensible variable name ;)