简体   繁体   English

将一列从一个工作簿复制并粘贴到另一个

[英]Copy and paste a column from one workbook to another

I have attached 2 screenshots:我附上了2张截图:

在此处输入图片说明

https://i.stack.imgur.com/54kBl.png

I copied and paste in the K column but the values don't match.我复制并粘贴在 K 列中,但值不匹配。 I want to copy and paste a columns from one workbook to another and default the values to that.我想将一列从一个工作簿复制并粘贴到另一个工作簿,并将值默认为该值。 I have the following code.我有以下代码。 My question is How do I make sure that the values from one source workbook defaults to the Target workbook?我的问题是如何确保一个源工作簿中的值默认为目标工作簿? I know I can use vlookup for that but I don't know how to use it.我知道我可以使用vlookup ,但我不知道如何使用它。

Sub test()
Dim wbkSrc As Workbook 'Source workbook
Dim wbkDest As Workbook ' Destination
Dim rSrc As Range 'Source range
Dim rDest As Range 'destination range

'set references to the workbooks

Set wbkDest = ActiveWorkbook
Set wbkSrc = Application.Workbooks.Open("C:\Users\jole.kk\AppData\Roaming\Microsoft\AddIns\CategoriesGLAccounts.xlsx")

'set references to the ranges

Set rDest = wbkDest.Worksheets("Report").Range("K:K")
Set rSrc = wbkSrc.Worksheets("Sheet1").Columns("B")
    
'copy from Source to Target

rSrc.Copy Destination:=rDest

'Close Source Workbook

wbkSrc.Close False

'Move

Columns("K:K").Select
Selection.Cut
Columns("J:J").Select
Selection.Insert Shift:=xlToRight

End Sub

I am not sure if this what you are looking for.我不确定这是否是您要找的。

Sub test()
    Dim wbkSrc As Workbook 'Source workbook
    Dim wbkDest As Workbook ' Destination
    Dim rSrc As Range 'Source range
    Dim rDest As Range 'destination range

    Application.ScreenUpdating = False
    
    'set references to the workbooks
    Set wbkDest = ThisWorkbook
    Set wbkSrc = Application.Workbooks.Open("C:\Users\jole.kk\AppData\Roaming\Microsoft\AddIns\CategoriesGLAccounts.xlsx")
    
    ' Find last row in 'Category Name' column (9) in sheet report
    Dim lRow As Integer: lRow = wbkDest.Sheets("Report").Cells(Rows.Count, 9).End(xlUp).Row
    
    'set references to the ranges
    Set rDest = wbkDest.Worksheets("Report").Range("K2:K" & lRow)
    Set rSrc = wbkSrc.Worksheets("Sheet1").Range("A1").CurrentRegion
        
    'Lookup GL Account by Category Name
    rDest.FormulaR1C1 = Application.WorksheetFunction.VLookup(rDest.Offset(0, -2), rSrc, 2, 0)
    
    'copy to values
    rDest.Copy
    rDest.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    Application.CutCopyMode = False
    
    'Close Source Workbook
    wbkSrc.Close False
    
    'Move
    Columns("K:K").Cut
    Columns("J:J").Insert Shift:=xlToRight
    
    Application.ScreenUpdating = True
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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