2014-02-21 58 views
0

我從一個工作簿複製和粘貼到另一個工作簿有多個定義的範圍。我編寫的代碼打開一個工作簿,該工作簿被定義爲一個變量,複製某些單元格,切換到「本書」並粘貼單元格。我想從作爲變量定義的工作簿中複製更多單元格,但無法弄清楚如何「切換」。我不想單獨打開工作簿3次。如何解決.open線路問題?消除「打開」變量定義工作簿3次?

謝謝

Sub MDVwk1() 
'turn off screen refreshing 
Application.ScreenUpdating = False 

'pick the correct timesheet 
TimeSheetMDV1 = Application.GetOpenFilename 

'Opens the workbook chosen for MDV week 1 

Workbooks.Open TimeSheetMDV1 
'Copies the project number cells and pastes them in the workbook under week 1 for MDV 
Range("B5:B100").Copy 
ThisWorkbook.Sheets("Mark").Activate 
'Pastes the copied cells 
Range("B10").PasteSpecial (xlPasteValues) 

'copies the project total hours from MDV Wk1 
Workbooks.Open TimeSheetMDV1 'THIS IS THE FIRST OPEN THAT I WANT TO ELIMINATE 
Range("L5:L100").Copy 

'Paste the copied cells 
ThisWorkbook.Sheets("Mark").Activate 
Range("C10").PasteSpecial (xlPasteValues) 

'opening the time sheet again to close it 
Workbooks.Open TimeSheetMDV1 
ActiveWorkbook.Close savechanges:=False 

'center the columns 
Columns("B:C").HorizontalAlignment = xlCenter 
End Sub 

回答

2

試試這個代碼:

Sub MDVwk1() 
    Dim wb As Workbook 
    Dim TimeSheetMDV1 
    Dim ws As Worksheet 

    'turn off screen refreshing 
    Application.ScreenUpdating = False 

    'pick the correct timesheet 
    TimeSheetMDV1 = Application.GetOpenFilename("Excel Files (*.xls*),*.xls*", 1, "Choose Excel file") 

    'if user doen't press cancel 
    If TimeSheetMDV1 <> False Then 

     'Opens the workbook chosen for MDV week 1 
     On Error Resume Next 
     Set wb = Workbooks.Open(TimeSheetMDV1) 
     On Error GoTo 0 
     'if workbook is succesfully opened 
     If Not wb Is Nothing Then 
      Set ws = ThisWorkbook.Sheets("Mark") 
      With wb 
       .Range("B5:B100").Copy 
       ws.Range("B10").PasteSpecial xlPasteValues 

       .Range("L5:L100").Copy 
       ws.Range("C10").PasteSpecial xlPasteValues 
      End With 
      'Copies the project number cells and pastes them in the workbook under week 1 for MDV 

      wb.Close SaveChanges:=False 
      Set wb = Nothing 

      'center the columns 
      ws.Range("B:C").HorizontalAlignment = xlCenter 
     End If 
    End If 
    Application.ScreenUpdating = True 
End Sub 

注意如何代碼打開工作簿:

Dim wb As Workbook 
'.... 
Set wb = Workbooks.Open(TimeSheetMDV1) 

現在你可以使用wb變量,打開工作簿工作。

另外我作了一些改進:

1)我在GetOpenFilename加入過濾器的文件格式:

TimeSheetMDV1 = Application.GetOpenFilename("Excel Files (*.xls*),*.xls*", 1, "Choose Excel file") 

2)如果用戶按下 「CANCEL」, TimeSheetMDV1將是False這就是爲什麼我加這個If聲明:

If TimeSheetMDV1 <> False Then 
    'do sth 
End if 

3)我還添加了特殊的變量爲您的工作表:

Dim ws As Worksheet 
'... 
Set ws = ThisWorkbook.Sheets("Mark") 
+1

工作就像一個魅力!我將不得不考慮所有的改進!非常感謝你。我相信我會回來的。再次感謝你。 – MarkMDV