for循环中的Excel VBA递增变量

时间:2014-11-06 23:59:13

标签: excel vba excel-vba userform

我仍然是VBA编程的新学习者,我遇到了一个似乎无法找到解决方案的问题。我正在尝试创建一个工作簿来处理食谱。我正在调用一个用户表单,用于在一个带有几个文本框输入的宏中添加一个配方(约96个)。当我输入所有成分,数量,单位并按下OK按钮时,我希望它将用户表单中的内容写入工作表。所有文本框都以一个以升序排列的数字命名(例如.txtIngredient1,.txtIngredient2,...)。是否可以使用for循环将Me.txtIngredientX.Value复制到工作表上的范围?

我当前代码的片段:

Sheets("Recipes").Range("B" & addatrow + 0) = Me.txtIngredient1.Value
Sheets("Recipes").Range("B" & addatrow + 1) = Me.txtIngredient2.Value
Sheets("Recipes").Range("B" & addatrow + 2) = Me.txtIngredient3.Value
Sheets("Recipes").Range("B" & addatrow + 3) = Me.txtIngredient4.Value
Sheets("Recipes").Range("B" & addatrow + 4) = Me.txtIngredient5.Value
Sheets("Recipes").Range("B" & addatrow + 5) = Me.txtIngredient6.Value
Sheets("Recipes").Range("B" & addatrow + 6) = Me.txtIngredient7.Value
Sheets("Recipes").Range("B" & addatrow + 7) = Me.txtIngredient8.Value
Sheets("Recipes").Range("B" & addatrow + 8) = Me.txtIngredient9.Value
Sheets("Recipes").Range("B" & addatrow + 9) = Me.txtIngredient10.Value
Sheets("Recipes").Range("B" & addatrow + 10) = Me.txtIngredient11.Value
Sheets("Recipes").Range("B" & addatrow + 11) = Me.txtIngredient12.Value
Sheets("Recipes").Range("B" & addatrow + 12) = Me.txtIngredient13.Value

我尝试过我唯一能做的事情,就是这样:

for i = 1 to 32
    Sheets("Recipes").Range("B" & addatrow - 1 + i) = me.txtIngredient & i.value

哪个不起作用。注意:addatrow是宏中的一个变量,用于指示下一个配方的插入位置。

非常感谢任何帮助!

谢谢!

3 个答案:

答案 0 :(得分:4)

试试这个:

请注意,nameForm必须是表单的名称,Me似乎不起作用。

for i = 1 to 32
    Sheets("Recipes").Range("B" & addatrow - 1 + i) = nameForm.Controls("txtIngredient" & i).Value

答案 1 :(得分:1)

此代码必须链接到UserForm代码页中的Ok按钮:

Sub Button_OK_Click 'Assuming the 'Ok' button is called Button_Ok on the userform

dim DATA () 'automatically declared as Variant, need to be Variant.
dim Sh as worksheet
dim i& ' declared as Long , this is our looping variable
redim DATA (1 to 96, 1 to 1) 'a one colone array with 96 rows
set Sh = thisworkbook.Sheets("Recipes")

with Me
    for i = 1 to 96
        DATA (i,1) = .Controls("txtIngredient" & i).Value
    next i
end with

with application
    .screenupdating = false
    .enableevents = false
    .calculation = XlManual
end with


with Sh
    .Range( .cells(addatrow,2) , .cells (addatrow+95 , 2) ).value2 = DATA 'write it to the sheet in a single line
end with

erase DATA
Set Sh = Nothing

with application
    .screenupdating = true
    .enableevents = true
    .calculation = XlAutomatic
end with

end sub

答案 2 :(得分:-1)

怎么样:

for i as integer = 1 to 32
    for each c as control in me.controls
        if typeof(c) is textbox andAlso c.name = "txtIngredient" & i.tostring then
            Sheets("Recipes").Range("B" & addatrow - 1 + i) = c.value
            exit for
        end if
    next c
next i

好问题,我经常想自己做这件事:)

(那个VB.NET代码,不知道有多少可以在VBA中运行,希望它有效)