2014-06-18 52 views
3

我有一些代碼,我發現,我想要什麼完美的作品,這是整個工作表從一個工作簿複製到另一個,但我希望定製它,並使其成爲一個對我來說更容易一些(所以我不必爲所有30張紙重新編碼),允許用戶準確指定他們要複製的紙張。需要用戶輸入口令代碼

  Sub Start() 
      Dim x As Workbook 
      Dim y As Workbook 

      '## Open both workbooks first: 
      Set x = Workbooks.Open("data workbook") 
      Set y = Workbooks.Open("destination workbook") 

      'This is where I would like the user to input the destination sheet in x: 
      x.Sheets("USER INPUT").Range("A1:z28").Copy 

      'Then paste data from x to y: 
      y.Sheets("STATIC SHEET").Range("A1").PasteSpecial 

      'Close x: 
      x.Close 
      End Sub 

我要的是一個彈出框,當宏運行,這將允許用戶輸入片(位於「數據的工作簿」)的名稱複製從信息出現,並會在訪問要複製的數據時自動將此輸入輸入到宏中。

回答

2

這有@TyMarc的回答納入您發佈的代碼,但它也有一個錯誤處理程序,這樣,如果用戶輸入不正確的名稱,它會給一個錯誤信息,並要求再次。

Sub Start() 
    On Error GoTo ErrorHandler 
    Dim x, y As Workbook 
    Dim inp as String 

    '## Open both workbooks first: 
    Set x = Workbooks.Open("data workbook") 
    Set y = Workbooks.Open("destination workbook") 

Label1: 

    inp = InputBox("Enter the name of the sheet to be copied") 

    'This is where I would like the user to input the destination sheet in x: 
    x.Sheets(inp).Range("A1:z28").Copy 

    'Then paste data from x to y: 
    y.Sheets("STATIC SHEET").Range("A1").PasteSpecial 

    'Close x: 
    x.Close 
    Exit Sub 'This is a crutial part otherwise it will finish the program and continue right into the error handler which will send it back to Label1 and start an infinite loop of death... 
ErrorHandler: 
    MsgBox("The input entered was not the name of a worksheet") 
    Resume Label1: 
End Sub 
1

你只需創建一個InputBox,InputBox的結果可以存儲在一個變量中,就像這樣。

Dim mySheet As String 
mySheet = Application.InputBox("Enter a sheet name") 

然後把

x.Sheets(mySheet).Range("A1:z28").Copy 

雖然你需要確保用戶輸入了一個良好的工作表名稱,否則你會得到一個錯誤。這裏是我的建議:

Set wsSheet = Sheets(mySheet) 
If wsSheet Is Nothing Then 
    'prompt the user again 
Else 
    'put your copy logic here 
End If 
+0

我照你說的,但是當我從「數據工作簿」拿了樣品名稱(我直接從工作簿複製的名稱,以避免錯誤輸入的話)我有一個不匹配的錯誤。但是當我點擊調試時,它突出了第一行代碼('Set mySheet ...')。我怎樣才能解決這個問題? – Reamithey

+0

對不起,請檢查新的編輯。 – TyMarc

+0

真棒,它工作!非常感謝。 – Reamithey