如何使用数组并在MsgBox VBA中显示它们

时间:2016-06-02 02:07:53

标签: arrays excel vba excel-vba

我需要编写一个sub,它从一个搜索列表中股票价格的输入框中获取一个参数。该子搜索了" B3:B20"的价格列表。当它找到超过此价格的第一个价格时,它会显示一个日期,该日期显示在msgbox中A列旁边的列中。这是我到目前为止的代码,但我无法弄清楚如何显示找到的价格的相应数据:(我相信问题与创建的数组有关)

Sub RecordHigh1()
Dim searchPrice As Currency
Dim rng As Range
Dim date1() As String
Dim price() As String
Dim nDates As Integer
Dim i As Integer



With wsData.Range("A3")
nDates = Range("A3", Range("A3").End(xlDown).Value)
ReDim date1(1 To nDates)
ReDim price(1 To nDates)
For i = 1 To nDates
    date1(i) = .Offset(i, 0).Value
    price(i) = .Offset(i, 1).Value
Next
End With


searchPrice = InputBox("Enter a Price")
Set rng = Range("B3", Range("B3").End(xlDown).Address)

For Each cell In rng
If cell.Value > searchPrice Then
MsgBox "The first date WalTech stock price exceeded " & searchPrice & " was & date(i) =.Offset(i, 0).Value & "
Else
MsgBox "WalTech stock has not exceeded this price"
End If
Next



End Sub

1 个答案:

答案 0 :(得分:0)

Option Explicit

Sub RecordHigh1()
Dim searchPrice As Currency
Dim rng As Range
Dim date1() As String
Dim price() As String
Dim nDates As Long
Dim i As Long '<~~ always better to use Long type instead of integer

Dim cell As Range


'With wsData.Range("A3")'<~~ wsData is not defined. or is it a Public variable?
With ActiveSheet.Range("A3") '<~~ otherwise set it to a specific sheet: With Worksheets("MySheet").Range("A3")
    nDates = .Range(.Cells, .Range("A3").End(xlDown)).Rows.Count
    ReDim date1(1 To nDates)
    ReDim price(1 To nDates)
    With .Range("A3")
        For i = 1 To nDates
            date1(i) = .Offset(i, 0).Value
            price(i) = .Offset(i, 1).Value
        Next i '<~~ always better to type the variable you want to iterate on
    End With
End With


searchPrice = InputBox("Enter a Price")
Set rng = ActiveSheet.Range("B3", ActiveSheet.Range("B3").End(xlDown).Address)'<~~ better to add sheet reference (ActiveSheet or Worksheets("MySheet") or wsData, this latter once you define it) 

For Each cell In rng
    If cell.Value > searchPrice Then
        MsgBox "The first date WalTech stock price exceeded " & searchPrice & " was " & cell.Offset(, -1)
    Else
        MsgBox "WalTech stock has not exceeded this price"
    End If
Next cell '<~~ always better to type the variable you want to iterate on

End Sub