2015-06-03 66 views
0

我有一段時間讓一個工作簿(「W1」)的代碼打開另一個工作簿(「W2」)並在W2中執行刪除。當我運行它時,它選擇W2中的範圍,但不會刪除選擇。我想通過命名W2來刪除,但是我迷失了方向。任何幫助將非常感激。使用另一個工作簿中的代碼從一個工作簿刪除數據範圍

我的代碼如下:

Sub Clear_FM_Contents() 

Dim f As FileDialog 
Dim varfile As Variant 
Dim path As Variant 

'Prompt the user to select the Excel File to Import 
Set f = Application.FileDialog(msoFileDialogFilePicker) 

'Error handling with file selector 
If f.Show = False Then 
    MsgBox "You clicked Cancel in the file dialog box." 
    End 
End If 

'Set the path of the User selected file 
For Each varfile In f.SelectedItems 
    path = varfile 
Next 

'Create the Excel object 
Dim xlApp As Excel.Application 
Set xlApp = CreateObject("Excel.Application") 
xlApp.Visible = True 

'Open the selected Excel file 
xlApp.Workbooks.Open path, True, False 

'Clear all Template Inputs 
With xlApp.ActiveWorkbook 
    .Sheets("Mrkt Data").Select 
    With xlApp.ActiveWorkbook.ActiveSheet 
     .Range("E36,E5,E7,E10,E13,E17,E39,J7:J11,J13:J20,J24:J29,J31:J33,J35,O21").Select 
     .Range("O21").Activate 
     xlApp.ActiveWorkbook.ActiveSheet.Selection.ClearContents 
    End With 
    'Close the Excel File 
    ActiveWorkbook.Save 
    ActiveWorkbook.Close 
End With 
'Close Excel 
xlApp.Quit 
'Eliminate the xl app object from memory 
Set xlApp = Nothing 

MsgBox "Model Inputs Cleared" 
End Sub 

回答

0

如果Select作品,然後只需用ClearContents取代它,而不是刪除其下的2號線,嘗試ActivateClear。我懷疑這個問題是ActivateO21正在清除,但沒有其他人。您也可以刪除Activate行,但我試圖清除Select不需要的實例。

With xlApp.ActiveWorkbook.ActiveSheet 
    .Range("E36,E5,E7,E10,E13,E17,E39,J7:J11,J13:J20,J24:J29,J31:J33,J35,O21").ClearContents 
End With 

代替

With xlApp.ActiveWorkbook.ActiveSheet 
    .Range("E36,E5,E7,E10,E13,E17,E39,J7:J11,J13:J20,J24:J29,J31:J33,J35,O21").Select 
    .Range("O21").Activate 
    xlApp.ActiveWorkbook.ActiveSheet.Selection.ClearContents 
End With 

你也可以壓縮With,做這一切在同一行,但太寬了,在這裏,所以我沒有做到這一點。

您還應該看看this post about not using Select.

相關問題