如何确定交易之间的最大值

时间:2018-02-08 16:34:16

标签: excel-vba vba excel

我有一个股票交易电子表格,我想确定交易之间的最大值和最小值。电子表格看起来像这样:

**Date**     **Stock  **Price**   **Action** **TradeNumber**
01/01/2018   Apple    1000.00           Buy    1
02/01/2018   Apple      995.25          -
03/01/2018   Apple      992.50          -
04/01/2018   Apple      987.50          -
05/01/2018   Apple      965.00         Close  1

我有一个包含交易号的列的范围。我想在这个范围内循环,每当我遇到一个有交易号的Cell时,我需要确定我持有Apples股票期间价格列的最大值。我正在努力解决最大公式的细胞范围,= Max(C2:C5 :)。任何想法或指示将不胜感激。

1 个答案:

答案 0 :(得分:0)

通过字典方法

建议通过数据字段数组获取数据并使用字典,我将唯一交易号记录为和引用数组索引与最高价格值一起作为项目。

此外我假设

  • 您的数据范围包含标题行
  • 您的日期范围,以计算最低/最高价格 包括以及购买日期作为< em>截止日期(确定如果不是这样,可以轻松更改这些值)。

<强>代码

Option Explicit
Sub Stock()
  Const colTrdNo As Integer = 5     ' column of TradeNo, e.g. 5th column
  Dim sTrdNo As String, sTrdNoOld As String
  Dim v, vKeys, vItems
  Dim i      As Long, n As Long
  Dim dHigh  As Double
  Dim dict   As Object              ' late bound dictionary
  Set dict = CreateObject("Scripting.Dictionary")
  Dim ws     As Worksheet
  Set ws = ThisWorkbook.Worksheets("Apple")   ' << change to your sheet name
' -----------------------
' I.  Get data
' -----------------------
' get last row in range
  n = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
' get data from column A:E to variant 1-based 2-dim datafield array
  v = ws.Range("A1:E" & n)
' ------------------------
' II. Use dictionary
' ------------------------
' check price when closing
  For i = 2 To UBound(v)                    ' << assume you omit title row
      sTrdNo = v(i, colTrdNo)
      If dict.exists(sTrdNo) Then           ' Close
         dict(sTrdNo) = dict(sTrdNo) & "," & i
         dict(sTrdNo) = dict(sTrdNo) & " => Min/Max $ " & getMinMax(v, dict(sTrdNo))
      ElseIf Len(sTrdNo) = 0 Then           ' do nothing (don't change ElseIf ORDER!)
      Else                                  ' new TradNo -> Buy
         dict.Add sTrdNo, i
      End If
  Next i
' ------------------------
' III. Get needed info
' ------------------------
    Debug.Print String(30, "~")
    vKeys = dict.keys()
    vItems = dict.items()
    For i = LBound(vKeys) To UBound(vKeys)
        Debug.Print i & " TradeNo " & vKeys(i) & ": Items " & vItems(i)
    Next i
' clear memory
  Set dict = Nothing
  Set ws = Nothing
End Sub

辅助功能

Function getMinMax(arr, ByVal s As String) As String
' Purpose: calculate highest price in array (given items range s)
Const colPRICE As Integer = 3
Dim i As Long, iStart As Long, iLast As Long
Dim dHigh As Double, dLow As Double
iStart = Val(Split(s, ",")(0)): iLast = Val(Split(s & ",", ",")(1))
dLow = 99999999999#
For i = iStart To iLast
    If arr(i, colPRICE) > dHigh Then dHigh = arr(i, colPRICE)
    If arr(i, colPRICE) < dLow Then dLow = arr(i, colPRICE)
Next i
getMinMax = dLow & " - " & dHigh
End Function