简体   繁体   中英

Copy and paste data between workbooks depending on drop-down choice

Just a quick one, I have coded a piece of VBA that copies and pastes data between two workbooks. However, I would like to be able to copy specific data across rather than the entire table. So workbook "x" I would like to filter column 'L' by a choice of a drop down box in workbook "y" - field "P14".

how would I do this, so that whatever the user chooses it filters and pastes that data into workbook y.

Code below for what I've done so far:

Private Sub CommandButton1_Click()

    Dim x As Workbook
    Dim y As Workbook
    Dim p As String

    Set p = y.Worksheets("Title").Cells(14, "P").Value
    Set x = Workbooks.Open("C:\Users\name\Desktop\Project
    Autonetics\CoreData")
    'x.Worksheets("Xero").Range("L1").AutoFilter Field:=1, Criteria:="p"
    With Xero
        .AutoFilterMode = False
        With .Range("L:L")
            .AutoFilter Field:=1, Criteria:="p"
            .SpecialCells (xlCellTypeVisible)
        End With
    End With
    Set y = ThisWorkbook
    x.Worksheets("Xero").Range("A1:L100000").Copy
    Application.DisplayAlerts = False
    y.Worksheets("Costings").Range("A1").PasteSpecial

    x.Close
End Sub

Here is something for you to work with. Personally I'm not such a On Error fan, but it would be legitimate use inside to check for a returned error when using SpecialCells .

Private Sub CommandButton1_Click()

Dim wb1 As Workbook, wb2 As Workbook
Dim sht1 As Worksheet, sht2 As Worksheet
Dim lc As Long, lr As Long
Dim rng As Range, str As String

'Set your two workbooks
Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Open("C:\Users\name\Desktop\ProjectAutonetics\CoreData")

'Set your two worksheets
Set sht1 = wb1.Worksheets("Title")
Set sht2 = wb2.Worksheets("Xero")

'Get your criteria ready
str = sht1.Range("P14").Value

'Get your range to filter ready
With sht2
    lr = .Cells(.Rows.Count, 12).End(xlUp).Row
    lc = .Cells(1, .Columns.Count).End(xlToLeft).Column
    Set rng = .Range(.Cells(1, 1), .Cells(lr, lc))
End With

'Apply filter and act if any hits
rng.AutoFilter 12, str
If rng.SpecialCells(12).Cells.Count > rng.Rows(1).Cells.Count Then
    rng.SpecialCells(12).Copy sht1.Cells(1, 1)
End If

'Close your second workbook
wb2.Close False

End Sub

I been quite extensive in the hope you can clearly see what is going on in this code.

Good luck.

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