VBA:筛选,从外部工作簿复制值,然后过去到活动工作簿

时间:2013-01-10 16:32:37

标签: vba excel-vba excel

我正在寻找这个问题的简单解决方案。

以下代码是我的尝试,源工作簿的过滤部分是否正确?

另外,我想确保在过滤和复制时保留了源工作簿

非常感谢任何想法!

Sub CopyFilteredValuesToActiveWorkbook()

    Dim sourceValues As Range, targetValues As Range

    Set sourceValues = Workbooks("\\Linkstation\rrm\X_DO_NOT_TOUCH_CC\MasterLogFile\Masterlogfile.xlsx").Worksheets("LogData").Columns("A:Z") 


    ActiveSheet.Range("$A$1:$H$3").AutoFilter Field:=3, Criteria1:="Opera" 


    Set targetValues = Workbooks("\\Linkstation\rrm\Campaign Creator\RAW DATA GENERATOR OPERA.xlsm").Worksheets("MLF").Columns("A:Z")             

    sourceValues.Copy Destination:=targetValues

End Sub

1 个答案:

答案 0 :(得分:1)

尝试这样的事情 - 将工作簿/工作表定义为变量可以更轻松地管理所有内容。我假设您希望宏为您打开其他工作簿 - 如果没有,代码可以轻松更改。

Sub CopyFilteredValuesToActiveWorkbook()

Dim wbSource As Workbook, wbDest As Workbook
Dim wsSource As Worksheet, wsDest As Worksheet
Dim rngSource As Range, rngDest As Range

Set wbSource = Workbooks.Open("\\Linkstation\rrm\X_DO_NOT_TOUCH_CC\MasterLogFile\Masterlogfile.xlsx", , True) 'Readonly = True
Set wsSource = wbSource.Worksheets("LogData")
wsSource.Range("$A$1:$H$3").AutoFilter Field:=3, Criteria1:="Opera"
Set rngSource = wsSource.Range("A:Z")

Set wbDest = ThisWorkbook
Set wsDest = wbDest.Worksheets("MLF")
Set rngDest = wsDest.Range("A:Z")

rngDest.Value = rngSource.Value 'Copies values over only, if you need formatting etc we'll need to use something else

wbSource.Close (False) 'Close without saving changes

End Sub