Copying and pasting data using VBA code

后端 未结 2 1953
遥遥无期
遥遥无期 2020-12-06 05:55

I have a button on a spreadsheet that, when pressed, should allow the user to open a file, then copy columns A-G of the spreadsheet \"Data\", then paste the data from those

相关标签:
2条回答
  • 2020-12-06 06:18

    Use the PasteSpecial method:

    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues
    

    BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).

    0 讨论(0)
  • 2020-12-06 06:30

    'So from this discussion i am thinking this should be the code then.

    Sub Button1_Click()
        Dim excel As excel.Application
        Dim wb As excel.Workbook
        Dim sht As excel.Worksheet
        Dim f As Object
    
        Set f = Application.FileDialog(3)
        f.AllowMultiSelect = False
        f.Show
    
        Set excel = CreateObject("excel.Application")
        Set wb = excel.Workbooks.Open(f.SelectedItems(1))
        Set sht = wb.Worksheets("Data")
    
        sht.Activate
        sht.Columns("A:G").Copy
        Range("A1").PasteSpecial Paste:=xlPasteValues
    
    
        wb.Close
    End Sub
    

    'Let me know if this is correct or a step was missed. Thx.

    0 讨论(0)
提交回复
热议问题