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

Posted

技术标签:

【中文标题】如何使用数组并在 MsgBox VBA 中显示它们【英文标题】:How to work with arrays and display them in a MsgBox VBA 【发布时间】:2016-06-02 02:07:53 【问题描述】:

我需要编写一个从输入框中获取单个参数的子程序,该输入框在列表中搜索股票价格。子搜索从“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

【问题讨论】:

您缺少" 所以searchPrice & " was & date(i) 应该是searchPrice & " was " & date(i) 并且末尾的和号和双引号需要删除。 @JerryJeremiah 代码仍然无法工作 @th65 - 代码在哪一行中断? 【参考方案1】:
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

【讨论】:

以上是关于如何使用数组并在 MsgBox VBA 中显示它们的主要内容,如果未能解决你的问题,请参考以下文章

VBA编程中MsgBox函数怎么用

VBA编程中MsgBox函数怎么用

VBA编程中MsgBox函数怎么用

当用户输入超过预期的参数时,强制 VBA 中的 UDF 显示 MsgBox?

VBA消息框(MsgBox)

VBA编程中MsgBox函数怎么用