循环然后运行宏

时间:2015-01-08 15:30:12

标签: excel vba excel-vba

我在名为“代码”

的工作表中有一列值

我有另一张“输入”,其中包含一个单元格B1,我必须在“代码”中输入一列值

然后我必须在“输入”B1中运行具有该值的宏。我有整列值来运行宏。如何创建循环来执行此操作?

2 个答案:

答案 0 :(得分:0)

您是否在验证输入?如果是这样,使用数据验证在Excel中有一种自动方式。查看Data对话框的Data Validation标签,然后选择带有Allow: List的{​​{1}}。

pic1

pic2

scr

答案 1 :(得分:0)

假设我已经理解了您要求的内容,您需要遍历代码范围并将其提供给另一个宏,这些宏将把这些代码放入'输入'!B1。您可以使用如下代码执行此操作:

Sub LoopMacro()

    Dim ws As Worksheet
    Dim rngCodes As Range
    Dim CodeCell As Range

    'Specify the range of cells that contain the codes
    'This example assumes they are in worksheet named 'Codes' and in column A starting at A1
    Set ws = Sheets("Codes")
    Set rngCodes = ws.Range("A1", ws.Cells(Rows.Count, "A").End(xlUp))

    'Then loop through each cell that contains the code and call your macro where you need to provide the input
    For Each CodeCell In rngCodes.Cells
        Call AcceptsInput(CodeCell.Value)
    Next CodeCell

End Sub

以下是AcceptsInput宏的代码:

Sub AcceptsInput(ByVal strCode As String)

    'This macro accepts the input
    'From here you can do what you want with it
    'Using your stated goal, you would put the code in worksheet named 'Input' in cell B1
    Sheets("Input").Range("B1").Value = strCode

    'Additional code goes here

End Sub