我是vba的新手,我想为自己的日常工作做一个宏。在这里,借助您的帮助,我成功地管理了其中的很大一部分,但我坚持了一节。
我想要的是:我有一个分析文件,它带有数月的代码开头,我要询问文件中有多少个月,并想知道其中的几个月。
Sub Makro2()
howmanymonths= Application.InputBox(prompt:=ActiveSheet.Name & " how many months?", Type:=1)
For first = 1 To howmanymonths
nay = Application.InputBox(prompt:=ActiveSheet.Name & " First?", Type:=1)
Next first
End Sub
例如,总共有3个月,我首先回答“ 3”,然后我回答了下一个问题“ 7”,所以不等于7,但是当其循环时下一个将是“ 8”和“ 9”
但是我如何创建nay1,nay2,nay3或直到最后几个月。
也许是更好的解决方案?请帮助我。
答案 0 :(得分:1)
在运行子程序时,不能在子程序中创建新变量。通常,您不需要。如果您不知道需要多少个单位,可以使用Array()
或List()
并向其中添加元素:
Sub TestMe()
Dim howManyMonths As Long
howManyMonths = Application.InputBox(prompt:=ActiveSheet.Name & Months count?",Type:=1)
Dim firstMonth As Long
firstMonth = Application.InputBox(prompt:=ActiveSheet.Name & " First?", Type:=1)
Dim someArray() As Long
Dim cnt As Long
ReDim someArray(howManyMonths - 1)
For cnt = LBound(someArray) To UBound(someArray)
someArray(cnt) = firstMonth + cnt
Next cnt
For cnt = LBound(someArray) To UBound(someArray)
MsgBox someArray(cnt)
Next cnt
End Sub
答案 1 :(得分:1)
这里是在字典中存储多个数据并使用其键检索它们的示例。
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
howmanymonths = Application.InputBox(prompt:=ActiveSheet.Name & " how many months?", Type:=1)
For first = 1 To howmanymonths
'Key is nay + numberindex
dict.Add "nay" & CStr(first), Application.InputBox(prompt:=ActiveSheet.Name & " First?", Type:=1)
Next first
MsgBox dict("nay1")
MsgBox dict("nay2")
MsgBox dict("nay3")