简体   繁体   中英

Name of source worksheet entered by user, copy data from source worksheet, paste to target worksheet

Dear stackoverflow experts,

I am new to vba and would like a simple macro for some copy-and-paste tasks. I have an xlsm file, containing multiple worksheets, name as follows CALCULATIONS LEMON ORANGE BANANA

I only know a very simple and popular macro for laymen.

Sub copyandpasterawdata()

  Workbooks("trymacro.xlsm").Worksheets("ORANGE").Range("A1:H2000").Copy

  Workbooks("trymacro.xlsm").Worksheets("CALCULATIONS").Range("A1").PasteSpecial Paste:=xlPasteValues

End Sub

I would like to make the source worksheet name "dynamic". That is, when I input "ORANGE" to cell I1 on worksheet CALCULATIONS and run the macro, data from worksheet ORANGE were copy-n-pasted, while when I input "LEMON" to cell I1 on worksheet CALCULATIONS and run the macro, data from worksheet LEMON will instead be copy-n-pasted.

Thank you.

John

Because you only want to copy values, you can use the Range.value2= RangeCopy.value2

Note that I1 is located in the paste area of your data,Let try:

 Option Compare Text
 Sub copyandpasterawdata()
        If ActiveSheet.Name <> "CALCULATIONS" Or Not (ThisWorkbook.Name Like "*trymacro*") Then Exit Sub

        ''check if sheetname
        'Dim sheetsname As Variant
        ' sheetsname = Array("LEMON", "ORANGE", "BANANA")
        'If IsEmpty(Filter(sheetsname, [I1].Value2, True, vbTextCompare)) Then Exit Sub
        '---------------------------------------
        Dim ws As Worksheet
        Dim isSheetname As Boolean
        For Each ws In Worksheets
            If [I1].Value2 Like ws.Name Then
                isSheetname = True
                Exit For
            End If
        Next ws
        If Not (isSheetname) Then Exit Sub

       'assign value
        Range("A1:H2000").Value = Worksheets([I1].Value2).Range("A1:H2000").Value
    End Sub

Here is shorter code:

 Sub copyandpasterawdata()
        If ActiveSheet.Name <> "CALCULATIONS" Or Not (ThisWorkbook.Name Like "*trymacro*") Then Exit Sub
 On Error Resume Next
       ' assign value
        Range("A1:H2000").Value = Worksheets([I1].Value2).Range("A1:H2000").Value
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM