2013-09-23 75 views
0

下面的代碼從「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

您必須聲明您的對象爲其他工作簿並分配給它。例如(未經測試)

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 
+0

首先,感謝你這麼積極主動配合你的專業知識:) 但是對於'子DoColumnCopy'我應該如何去使用'thisWb'&'destWb'? 'thisWb.Sheets(「sheet1」)'不會這樣做...... – GimGanDi

+0

什麼是「蘋果」和「橘子」在這裏?某些列的值?他們是從一些細胞中挑選出來的嗎? –

+0

Apple&Orange是'DoColumnCopy'的文本字符串,它在A1行中搜索「Apple」,抓取該列中的數據(當前工作簿),並在用戶打開的工作簿** sheet1的A1行中搜索「orange」 *並粘貼數據。 – GimGanDi

相關問題