消除“打开”variables定义工作簿3次?

有多个定义的范围,我从一个工作簿复制和粘贴到另一个。 我写的代码打开一个定义为variables的工作簿,复制某些单元格,切换到“thisworkbook”并粘贴单元格。 我想从作为variables定义的工作簿复制更多的单元格,但无法弄清楚如何“切换”。 我不想单独打开工作簿3次。 如何绕开.open线?

谢谢

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 

试试这个代码:

 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) 

现在您可以使用wbvariables来处理打开的工作簿。

另外我做了一些改进:

1)我在GetOpenFilename添加了文件格式的filter:

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

2)如果用户按“取消”, TimeSheetMDV1将是False ,这就是为什么我加了这个If语句:

 If TimeSheetMDV1 <> False Then 'do sth End if 

3)我也为你的工作表添加了特殊的variables:

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