[英]Excel VBA incrementing variable in for loop
我仍然是VBA編程的新手,遇到了一個我似乎找不到解決方案的問題。 我正在嘗試創建一個工作簿來處理食譜。 我正在調用一個用戶窗體,該窗體用於在具有幾個文本框輸入(其中有〜96個)的宏中添加配方。 輸入所有成分,數量,單位並按確定按鈕后,我希望它將用戶表單中的內容寫到工作表中。 所有文本框均以數字升序命名(例如.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是宏中的變量,指示下一個配方應插入的位置。
任何幫助是極大的贊賞!
謝謝!
嘗試這個:
請注意, nameForm
必須是您的表單的名稱,With Me
似乎不起作用。
for i = 1 to 32
Sheets("Recipes").Range("B" & addatrow - 1 + i) = nameForm.Controls("txtIngredient" & i).Value
此代碼必須鏈接到用戶窗體代碼頁內的“確定”按鈕:
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代碼,不知道其中有多少將在VBA中工作,希望它能工作)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.