需要用户输入来指示代码

时间:2014-06-18 15:09:47

标签: excel vba user-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

我想要的是在运行宏时会出现一个弹出框,允许用户输入工作表的名称(位于"数据工作簿")来复制信息,以及访问要复制的数据时,将自动将此输入输入宏。

2 个答案:

答案 0 :(得分: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 :(得分: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