2

I have to pass 2 cells (reference or value) from one sub to another sub so that the value in the first cell is copied and pasted to the other cell. Since it is required for multiple cell combinations, I want to get it done by passing the cell (reference or value) from one subroutine to other.

I've tried the following code and combination with Byref and ByVal options. But unable to get the desired results. Essentially, in the below code, whatever value is present in cell E1792 should be copy-pasted to C1799 as Value and Number formatted.

Private Sub Copy_Val(ByRef CopyFrom As Range, ByRef PasteTo As Range)
Application.ScreenUpdating = False

    Range(CopyFrom).Select
    Selection.Copy
    Range(PasteTo).Select

    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

End Sub

Sub Apply_Filter()
    Dim CpFrm As Range
    Dim PstTo As Range
    Set CpFrm = Range("E1792")
    Set PstTo = Range("C1799")
    Call Copy_Val(CpFrm, PstTo)
End Sub

Sometimes I get Type Mismatch error, and sometimes "400" error. Expected output is that the cell value present in cell E1792 should be copy-pasted to C1799 as Value and Number formatted.

Any help in fixing this will be appreciated.

1
  • Remember, you always need to specify the workbook and worksheet for each range object Commented May 28, 2019 at 12:18

2 Answers 2

3

Since CopyFrom and PasteTo are Range objects, you don't need to use Range(). You can also eliminate the Select part and simplify your function considerably:

Private Sub Copy_Val(ByRef CopyFrom As Range, ByRef PasteTo As Range)
Application.ScreenUpdating = False

    CopyFrom.Copy
    PasteTo.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

End Sub
Sign up to request clarification or add additional context in comments.

Comments

1

You could try:

Option Explicit

Public Sub Copy_Val(ByVal CopyFrom As Range, ByVal PasteTo As Range)

    Application.ScreenUpdating = False

        CopyFrom.Copy
        PasteTo.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
            xlNone, SkipBlanks:=False, Transpose:=False

    Application.ScreenUpdating = True

End Sub

Sub Apply_Filter()

    With ThisWorkbook.Sheets("Sheet1")

        Call Copy_Val(.Range("E1792"), .Range("C1799"))

    End With

End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.