2017-05-17 116 views
1

我有兩個工作簿,wbwb2。我想從表Nov做,將粘貼範圍(使用設置值)複製到不同的工作簿

  1. 將數據複製到在wb //這部分表Nov Temp什麼,代碼工作。

  2. wb的具體範圍複製到wb2。 //我嘗試使用Rng來設置值,但由於我處理範圍的方式而無法工作。 Rng in (myRange = sht.Rng.Value)突出顯示爲

    編譯錯誤;方法或數據成員未找到。

請幫助...

Option Explicit 

Sub cont() 
    Application.Volatile 

    Dim sht As Worksheet 
    Dim myRange As Variant 
    Dim Rng As Range 
    Dim Lastrow, ecol, eRow As Integer 
    Dim station As String 
    Dim wb As Workbook, wb2 As Workbook 

    Set wb = ActiveWorkbook 
    wb.Sheets("Nov").Activate 

    eRow = Cells(Rows.Count, 2).End(xlUp).Row 
    station = Range("B2").Value 
    Range(Cells(2, 2), Cells(eRow, 2)).Copy 
    MsgBox "Transfer data for station: " & station 

    On Error GoTo 0 

    wb.Sheets("Nov Template").Activate 
    Set sht = ActiveWorkbook.Sheets("Nov Template") 
    ecol = sht.UsedRange.Columns.Count 

    sht.Range(Cells(1, 2), Cells(eRow, 2)).PasteSpecial xlPasteValues 
    With ActiveSheet.UsedRange 
     Lastrow = .Rows(.Rows.Count).Row 
     Set Rng = Range(Cells(1, "C"), Cells(Lastrow, ecol)) 
     myRange = sht.Rng.Value 
    End With 

    Workbooks.Open "G:\Mean2std\Merge NDj (2).xlsm" 
    Set wb2 = ActiveWorkbook 
    wb2.Worksheets("GM").Range("B3:AO32").Value = myRange 
    wb2.Close SaveChanges:=True 
End Sub 
+0

附註:(1)'On Error GoTo 0'在這裏完全沒用。 (2)您應該閱讀並遵循[VBA最佳實踐](http://stackoverflow.com/documentation/excel-vba/1107/vba-best-practices)的整個指南,如果您遵循該指南將解決許多問題嚴格。 (3)'Dim Lastrow,ecol,eRow As Integer'只聲明其他變量的最後一個變量保持'Variant'並且從不使用'Integer'使用'Long'代替:'Dim Lastrow As Long,ecol As Long,eRow As Long' –

+0

@Peh,我的意圖使用錯誤轉到0是在循環中應用此代碼時提供轉義。謝謝我會通讀你的建議。 –

+0

@Peh,你能解釋你的3)句子嗎?「只聲明最後一個變量其他變量」?什麼是使用長而不是整數的重要性? –

回答

0

現在它的工作原理,去除myRange和僅使用RNG。

Option Explicit 

Sub cont() 
    Application.Volatile 

    Dim sht As Worksheet 
    'Dim myRange As Variant 
    Dim Rng As Range 
    Dim Lastrow, ecol, eRow As Long 
    Dim station As String 
    Dim wb As Workbook, wb2 As Workbook 

    Set wb = ActiveWorkbook 
    wb.Sheets("Nov").Activate 

    eRow = Cells(Rows.Count, 2).End(xlUp).Row 
    station = Range("B2").Value 
    Range(Cells(2, 2), Cells(eRow, 2)).Copy 
    MsgBox "Transfer data for station: " & station 

    wb.Sheets("Nov Template").Activate 
    Set sht = ActiveWorkbook.Sheets("Nov Template") 
    ecol = sht.UsedRange.Columns.Count 

    sht.Range(Cells(1, 2), Cells(eRow, 2)).PasteSpecial xlPasteValues 
    With ActiveSheet.UsedRange 
     Lastrow = .Rows(.Rows.Count).Row 
     Set Rng = Range(Cells(1, "C"), Cells(Lastrow, ecol)) 
     'myRange = sht.Rng.Value 
    End With 

    Workbooks.Open "G:\Mean2std\Merge NDj (2).xlsm" 
    Set wb2 = ActiveWorkbook 
    'wb2.Worksheets("GM").Range("B3:AO32").Value = myRange 
    wb2.Worksheets("GM").Range("B3:AO32").Value = Rng.Value 
    wb2.Close SaveChanges:=True 
End Sub 
相關問題