【问题标题】:Running a macro a dynamic # of times动态运行宏 # 次
【发布时间】:2014-03-03 20:28:50
【问题描述】:

我有一个用户表单,用户可以在其中在文本字段中输入值,然后将其放入列表框中,该列表框始终是动态数量的条目。当他们选择“完成”时,我如何让 VBA 分别识别每一行?

他们正在输入属性名称,我有一个代码,上面写着复制模板 x 次并将每个重命名为已输入的值。

我想说的是:

Dim cellNumber As Integer
Dim property As ListBox.Items

cellNumber = 11 
For Each property In ListBox1
   Range("B" & cellNumber).Value = property

   'copying template and renaming it
   Sheets("Template").Copy After:=Sheets("Template")
   ActiveSheet.Name = property 

【问题讨论】:

  • “条目”只是用户点击返回吗?即它是一个由换行符分隔的列表?
  • 那么,它是一个文本框,并且用户输入了一些类似逗号分隔的条目吗?像 prop1,prop2,prop3,prop4 等等...或者它是多个文本框,每个文本框可能有也可能没有值?
  • 哦,列表框中的条目数量未知,您希望代码循环遍历其中的每个条目吗?

标签: excel vba listbox listboxitem


【解决方案1】:

试试这个:

 Dim cellNumber As Integer
 Dim property As string


cellNumber = 11 
For i = 0 to listbox1.listcount - 1    '-1 because the .list starts at 0
    property = listbox1.list(i)
    Range("B" & cellNumber).Value = property

'copying template and renaming it
    Sheets("Template").Copy After:=Sheets("Template")
    ActiveSheet.Name = property
next

这将处理该列表框中的所有条目。

如果您想知道如何填充它:

如果您有 1 个文本框,用户可以在其中输入多个逗号分隔的属性,例如 prop1、prop2、prop3 等。那么您会使用

dim values as variant
values = split(txtbox.text, ",") ' where you can use any delimiter

那么你会这样做:

dim val as string
for each val in values
    listbox1.add(val)
next

如果您有多个文本框,您只需遍历表单上的控件,检查类型名称并在它们不为空时添加值。喜欢:

dim ctrl as control
for each ctrl in form.controls
    if typename ctrl = "Textbox" then
        if not ctrl.text= "" then 
            listbox1.add(ctrl.text)
        end if
    end if
next

【讨论】:

    猜你喜欢
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多