
Originally Posted by
davesexcel
It looks like you never Dim'd the workbooks.
See if this works for you.
Public Dim the Workbooks at the Start of the Workbook Module.
It should pass down to the Sheet_Change code.
Public Dwb As Workbook, Swb As Workbook
Private Sub Workbook_Open()
Dim newFileName As String, newFilePath As String
Dim Sws As Worksheet, Dws As Worksheet, ws As Worksheet
Set Swb = ActiveWorkbook
newFilePath = Swb.Path & "\"
.......
Thanks daves but still I am having issue with my code not getting any error but not working as required
Public Dwb As Workbook, Swb As Workbook
Private Sub Workbook_Open()
Dim newFileName As String, newFilePath As String
Dim Sws As Worksheet, Dws As Worksheet, ws As Worksheet
Set Swb = ActiveWorkbook
newFilePath = Swb.Path & "\"
newFileName = Day(Date) & "-" & Format(Date, "mmm") & " " & Format(Now, "hh-mm-ss")
Swb.Sheets.Copy
Set Dwb = ActiveWorkbook
Dwb.SaveAs newFilePath & newFileName
For Each Sws In Swb.Worksheets
For Each Dws In Dwb.Worksheets
If Dws.Name = Sws.Name Then
Dws.Cells.Clear
Sws.Rows(1).Copy Dws.Range("A1")
Sws.Rows(2).Copy Dws.Range("A2")
Exit For
End If
Next Dws
Next Sws
Swb.Activate
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
Dim Sws As Worksheet
Dim ws As Worksheet
Dim lastRow As Long, Scol As Long, lastColumn As Long
Dim Drng As Range, DO1rng As Range, cell As Range
Set Sws = Swb.ActiveSheet
Scol = Target.Column
For Each ws In Dwb.Worksheets
If ws.Name = Sws.Name Then
lastColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
lastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
If Target.Column = 2 Then
Set Drng = ws.Range(ws.Cells(1, Scol), ws.Cells(lastRow, Scol))
Set DO1rng = ws.Range(ws.Cells(1, Scol + 1), ws.Cells(lastRow, Scol + 1))
'count the number of cells with in a range
If WorksheetFunction.CountIf(Drng, Target) = 0 And WorksheetFunction.CountIf(DO1rng, Target.Offset(0, 1)) = 0 Then
Target.EntireRow.Copy ws.Range("A" & Rows.Count).End(3)(2)
Else
Set Drng = ws.Range(ws.Cells(1, Scol + 1), ws.Cells(lastRow, Scol + 1)) 'Returns a Range object that represents a cell or a range of cells
Set cell = Drng.Find(Target.Offset(0, 1)) 'Finds specific information in a range
ws.Cells(cell.Row, Scol) = Target
End If
ElseIf Target.Column > 1 Then
lastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
Set Drng = ws.Range(ws.Cells(1, Scol - 1), ws.Cells(lastRow, Scol - 1))
If WorksheetFunction.CountIf(Drng, Target.Offset(0, -1)) = 0 Then
Target.EntireRow.Copy ws.Range("A" & Rows.Count).End(3)(2)
Else
Set cell = Drng.Find(Target.Offset(0, -1))
ws.Cells(cell.Row, Scol) = Target
End If
End If
End If
Next ws
Swb.Save
Dwb.Save
End Sub
My new code after your suggestion
Bookmarks