tags:

views:

41

answers:

1

I have the below code that is suppose to copy data from an excel file I receive in a email and paste it to another file on the row that has the same date. When I try and run the macro it says there is an error. Can anyone look at my code and direct me as to where my error is. I am fairly new to coding and creating macros.

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
Dim WS As Worksheet


On Error GoTo Err_Execute

Set WS = Workbooks("McKinney Daily Census Template OCT 10.xls").Sheets("McKinney")


'Retrieve date value to search for
WS = Workbooks("McKinney Daily Census Template OCT 10.xls").Cell("B15").Value

Sheets("Input").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

    'Encountered blank cell in row 2, terminate search
    If Len(Cells(2, LColumn)) = 0 Then
        MsgBox "No matching date was found."
        Exit Sub

    'Found match in row 2
    ElseIf Cells(2, LColumn) = LDate Then

        'Select values to copy from "McKinney" sheet
        Sheets("McKinney Daily Census Template OCT 10.xls").Select
        Range("C15:I15").Select
        Selection.Copy

        'Paste onto "Key Indicator" sheet
        Sheets("Input").Select
        Cells(3, LColumn).Select
        Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=False

        LFound = True
        MsgBox "The data has been successfully copied."

    'Continue searching
    Else
        LColumn = LColumn + 1
    End If

Wend

On Error GoTo 0

Exit Sub

Err_Execute:
MsgBox "An error occurred."

End Sub
A: 

What line generates the error? It seems that your variable LDate never recieves a date. May be instead of

WS = Workbooks("McKinney Daily Census Template OCT 10.xls").Cell("B15").Value 

you meant to write

LDate = Workbooks("McKinney Daily Census Template OCT 10.xls").Cell("B15").Value 

All this looks like pretty lenghty and dangerous code: why not a) get both the date from your input sheet and the data you want to copy (looks like you could put these in an array with a for loop) and then b) search for the cell that contains the date you want (1 statement) to retrieve the row of the cell that matches the date you want, and then c) loop the data from the array to the sheet.

@user 471807...can you give me an example of what that code would look like?
Edmond