复制&在多个工作簿之间粘贴某些单元格

时间:2013-09-23 22:25:15

标签: excel vba excel-vba excel-2010

下面的代码是从“data.xlsx”excel工作簿运行的,应该提示用户打开excel工作簿文件并将数据从“data.xlsx”复制到用户打开的excel工作簿中。

Sub test()
    Dim ToSheet As Worksheet
    Dim FromBook As String
    Dim FromSheet As Worksheet
     '--------------------------------------------------------------------
    Set ToSheet = ActiveSheet
    FromBook = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx, All Files (*.*), *.*", 1, "Select Log File ")
    If FromBook = "False" Then Exit Sub
    Workbooks.Open FromBook
    Set FromSheet = ActiveSheet.Worksheets("Sheet1")
     '--------------------------------------------------------------------
     'Copy / Paste Data
   ToSheet.Activate
   DoColumnCopy "Apple", "Orange"
End Sub
'-------------------------------------------------------
'I need below code to work between the workbook, currently it 
'only works between the worksheet.

'Get data from FromColName and copy to ToColName
Sub DoColumnCopy(FromColName As String, ToColName As String)

    Dim rng As Range, rngCopy As Range, rng2 As Range

    Set rng = workbooks(1).Sheets("data").Rows(1).Find(What:=FromColName, LookIn:=xlValues, _
                                  LookAt:=xlWhole)
    If Not rng Is Nothing Then

        Set rngCopy = workbooks(1).Sheets("data").Range(rng).End(xlDown)

        Set rng2 = workbooks(2).Sheets("log").Rows(1).Find(What:=ToColName, LookIn:=xlValues, _
                                   LookAt:=xlWhole)

        If Not rng2 Is Nothing Then rngCopy.Copy rng2.Offset(1, 0)

    End If
End Sub

如何修复代码的workbooks(2).sheets...部分,以便知道用户打开的工作簿的名称?或者如果有多个工作簿打开了?

我欢迎如果你有更好的方法这样做 非常感谢你!

1 个答案:

答案 0 :(得分:1)

您必须为其他工作簿声明对象并分配给它。例如(UNTESTED)

Sub test()
    Dim thisWb As Workbook, destWb As Workbook
    Dim ToSheet As Worksheet, FromSheet As Worksheet
    Dim FromBook As String

    '~~> Current workbook and the sheet
    Set thisWb = ThisWorkbook
    Set ToSheet = thisWb.ActiveSheet

    FromBook = Application.GetOpenFilename( _
    "Excel Files (*.xlsx), *.xlsx, All Files (*.*), *.*", 1, "Select Log File ")
    If FromBook = "False" Then Exit Sub

    '~~> This is how you store it in an object and then use it
    Set destWb = Workbooks.Open(FromBook)
    Set FromSheet = destWb.Worksheets("Sheet1")

    '
    '~~> Rest of your code
    '
End Sub