2014-05-16 138 views
0

我想將一個excel文件中的值複製到另一個excel文件,但是在我的項目的後期階段,我可能需要交叉檢查該值,然後將其粘貼到新的excel文件。所以我不想一次複印整張紙。我想按值複製一個值。將單元格的值從一個excel複製到另一個excel

我能夠打開並切換到Excel文件,但我無法複製和粘貼值。 以下是我試過的代碼 -

Private Sub CommandButton1_Click() 
Dim x As Long 
Dim NumRows As Long 
Set fromwb = Workbooks.Open("G:\Excel\From.xlsx") 
Set towb = Workbooks.Open("G:\Excel\To.xlsx") 
fromwb.Activate 
NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count 
ReDim a(1 To NumRows) 

For x = 1 To NumRows 
    fromwb.Activate 
    a(x) = Cells(x, 1).Value 

    towb.Activate 
    Cells(x, 1).Value = a(x) 
Next x 

End Sub 

感謝您的期待。

回答

0

下面嘗試一下代碼宏代碼。我希望評論非常清楚!

Option Explicit 
Private Sub CommandButton1_Click() 

Dim SourceBook As Workbook, DestBook As Workbook 
Dim SourceSheet As Worksheet, DestSheet As Worksheet 
Dim Index As Long, NumRows As Long 
Dim ValidCheck As Boolean 

'set references up-front 
Set SourceBook = Workbooks.Open("G:\Excel\From.xlsx") 
Set SourceSheet = SourceBook.ActiveSheet 
With SourceSheet 
    NumRows = .Range("A", .Rows.Count).End(xlUp).Row '<~ last row in col A 
End With 
Set DestBook = Workbooks.Open("G:\Excel\To.xlsx") 
Set DestSheet = DestBook.ActiveSheet 

'loop through col A and write out values to destination 
For Index = 1 To NumRows 

    '... 
    'do your value validation 
    'in this space using ValidCheck 
    '... 

    If ValidCheck Then '<~ if true write to Dest 
     DestSheet.Cells(Index, 1) = SourceSheet.Cells(Index, 1) 
    End If '<~ if not, do not write to Dest 

Next Index 

End Sub 
+0

上面用到的用於確定迭代行數的方法經過了很好的審查,並由S.O.的VBA嚮導推薦。我保留這個帖子的書籤,以防我需要快速審查:http://stackoverflow.com/questions/11169445/error-finding-last-used-cell-in-vba –

0

你只需要指定單元格等於單元格,不需要循環任何東西。

Workbooks("To.xlsx").Sheets("ToSheetNameHere").Range("rangehere").Value = Workbooks("From.xlsx").Sheets("FromSheetNameHere").Range("rangehere").Value 

請記住,如果你有工作簿中的(),他們將.XLSM,而不是原來的.xlsx

相關問題