使用Application.Selection和Application.InputBox将两列相乘

时间:2014-12-08 21:59:22

标签: arrays function excel-vba vba excel

VBA非常新,想要了解更多。我尝试使用电子表格中的公式轻松完成某些操作,但我想学习如何编写代码。

我基本上想告诉用户选择两个相同长度的单元格区域并将它们相乘以返回一个值。出于我用它的目的,我根据市场价格和股票数量来计算股票的市场价值。

我已经完成了设置,但我不知道自己做什么来加倍或返回值

Sub CalculateMV()

Dim Rng As Range Dim Rng2 As Range

设置Rng = Application.Selection 设置Rng = Application.InputBox("选择所有市场价值"," MV计算器",类型:= 8)

Dim rng3 As Range

设置rng3 = Application.Selection 设置rng3 = Application.InputBox("选择所有市场价值"," MV计算器",类型:= 8)

对于Rng中的每个Rng2

是否有一些(基本上)缺少的东西,比如数组或我需要编写一个函数?

提前致谢。

1 个答案:

答案 0 :(得分:0)

首先,由于您的范围需要大小相同,因此您需要执行检查以要求用户再次尝试"如果范围彼此不相等,或者其中一个范围超过1列宽。

然后,您需要使用For循环来乘以每个单元格。这是我提出的代码。目前它只返回调试/立即窗口的值(在VBA中按Ctrl + G查看它),因为我不知道你想要实际去哪里,但这应该让你开始。

Sub CalculateMV()

    On Error Resume Next

    Dim Rng1 As Range, Rng2 As Range
    Dim RowCount As Long, i As Long
    Dim Result As Double

Lbl_TryAgain1:
    Set Rng1 = Application.InputBox("Select All Market Values, 1st Range", "MV Calculator", Type:=8)
    If Rng1.Columns.Count > 1 Then
        MsgBox "Each range must have a maximum of one column. Please try again.", vbExclamation
        Set Rng1 = Nothing
        GoTo Lbl_TryAgain1
    End If
Lbl_TryAgain2:
    Set Rng2 = Application.InputBox("Select All Market Values, 2nd Range", "MV Calculator", Type:=8)
    If Rng2.Columns.Count > 1 Then
        MsgBox "Each range must have a maximum of one column. Please try again.", vbExclamation
        Set Rng2 = Nothing
        GoTo Lbl_TryAgain2
    ElseIf Rng1.Rows.Count <> Rng2.Rows.Count Then
        MsgBox "Each range must have the same number of rows. Please try again.", vbExclamation
        Set Rng2 = Nothing
        GoTo Lbl_TryAgain2
    End If

    RowCount = Rng1.Rows.Count

    For i = 1 To RowCount
        Result = Val(Rng1.Cells(i, 1)) * Val(Rng2.Cells(i, 1))
        Debug.Print Result
    Next i

End Sub