Excel VBA在for循环中递增variables

我仍然是VBA编程的新学习者,而且遇到了一个我似乎无法find解决scheme的问题。 我正在尝试创build一个工作簿来处理食谱。 我正在调用一个用户窗体,用于在一个macros中添加一个配方,并带有几个文本框input(〜96个)。 当我input所有成分,数量,单位,然后按确定button,我想要它写在用户表单中的内容到工作表。 所有的文本框都以一个数字按升序排列(如.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是macros中的一个variables,它决定了下一个配方的插入位置。

任何帮助是极大的赞赏!

谢谢!

尝试这个:

请注意, nameForm必须是您的窗体的名称,与Me似乎不工作。

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

此代码必须链接到用户窗体的代码页内的确定button:

 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 

怎么样:

 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代码,不知道有多less将在VBA中工作,希望它的工作原理)