需要用户input来指定代码

我有一些代码,我发现,完美的作品,我想要的,这是整个工作表从一个工作簿复制到另一个,但我希望定制它,使它更容易一点(所以我不所有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 

我想要的是一个popup框,当macros运行,将允许用户input一个工作表(位于“数据工作簿”)复制信息的名称,并将自动input到macros访问要复制的数据时。

这有@TyMarc的答案纳入您发布的代码,但它也有一个error handling程序,以便如果用户input不正确的名称,它会给出一个错误消息,再次询问。

 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 

你只需要创build一个InputBox,InputBox的结果可以存储在一个variables中,就像这样。

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

然后放

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

虽然你需要确保用户input一个好的表名,否则你会得到一个错误。 这是我的build议:

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