应该很简单,基于用户输入的数组循环

时间:2016-10-04 13:09:11

标签: arrays vba loops user-input

我需要一个电子表格,提示用户输入以下内容:

  • 他们测试过的次数

  • 启动电压

  • 电路中的电阻数量

  • 电阻之间的距离

  • 每个电阻器的电阻

我需要输出以下内容:

  • 等效电阻
  • 当前理论
  • 每个停止串的电压
  • 基于输入值的响应

我设法让用户输入工作。我相信我的问题是在循环中设置一个数组,所以我可以得到所有数据的总和,比如等效阻力。

我需要一种方法来执行诸如在记录后对某组输入值进行求和等功能。我认为这是一个阵列,但我仍在教自己VBA。任何帮助表示赞赏!

    Private Sub CommandButton21_Click()

TrialRuns = InputBox("How many separate voltage sources have you tested?")

Dim x As Integer
For x = 1 To TrialRuns

TrialName = InputBox("Please input the name or some other type of identifying quality (ie. Level 1 load side)")
Rows("2").Insert Shift:=x1ShiftDown, CopyOrigin:=x1FormatFromRightorBelow
StartingVoltage = "What is the starting voltage?"
Msg = "How many resistors/loads do you have?"
VoltageInput = InputBox(StartingVoltage)

ActiveSheet.Range("A2").Value = TrialName
ActiveSheet.Range("B2").Value = VoltageInput
QtyEntry = InputBox(Msg)
ActiveSheet.Range("C2").Value = QtyEntry


Dim i As Integer

For i = 1 To Range("C2").Value

    Rows("3").Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow
ResistanceValue = InputBox("Hey dude, what is the resistance value in ohms?")
RunLength = InputBox("Cool! How far is it (in feet) from the previous load? Use distance from voltage source if this is the first load.")

ActiveSheet.Range("G3").Value = RunLength
ActiveSheet.Range("D3").Value = ResistanceValue
ActiveSheet.Range("E3").Value = 1 / ResistanceValue

Next i

Next x


End Sub

1 个答案:

答案 0 :(得分:0)

我不完全确定我理解你在寻找什么,但你应该能够在不使用数组的情况下得到每个组的总和。

在此代码块中添加以下内容:

Dim i As Integer
Dim runTotal As Double
Dim resistTotal As Double

runTotal = 0
resistTotal = 0

For i = 1 To Range("C2").Value

    Rows("3").Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow
    ResistanceValue = InputBox("Hey dude, what is the resistance value in    ohms?")
    RunLength = InputBox("Cool! How far is it (in feet) from the previous     load? Use distance from voltage source if this is the first load.")

    ActiveSheet.Range("G3").Value = RunLength
    ActiveSheet.Range("D3").Value = ResistanceValue
    ActiveSheet.Range("E3").Value = 1 / ResistanceValue

    runTotal = runTotal + RunLength
    resistTotal = resistTotal + ResistanceValue

    If i = Range("C2").Value Then
        ActiveSheet.Range("G4").Value = runTotal
        ActiveSheet.Range("D4").Value = runTotal
    End If

Next i

如果这不能解决您的问题并且您想要使用数组,则可以添加类似于以下内容的内容:

Dim runArr() As Double
ReDim runArr(1 To QtyEntry)

For i = 1 To Range("C2").Value
    '...
    runArr(i) = RunLength
Next i