需要MsgBox来显示数组中的单元格旁边的Excel单元格
这里是代码:
For R = 5 To 145 If Worksheets("CHPSpecs").Cells(R, 4).Value >= 0.9 * CHPSize And Worksheets("CHPSpecs").Cells(R, 4).Value <= 1.1 * CHPSize Then j = 0 ReDim Preserve eleOutput(j) eleOutput(j) = Worksheets("CHPSpecs").Cells(R, 3).Value End If Next R For j = LBound(eleOutput) To UBound(eleOutput) If eleOutput(j) <= compareNum Then MsgBox ??????? End If Next j
为了更好的观看,我拿走了一些代码,但这是我遇到的麻烦。 所以我让VBA看下一个指定的列,如果这些单元格中的值匹配条件,那么它们被存储在一个名为eleOutput(j)
的数组中。
然后,我想比较数组的variablescompareNum
,如果这个If语句是真的,我想MsgBox
数组eleOutput(j)
中包含的单元格旁边的单元格。
假设一切都被声明,并且If statements
正确完成,那么我该如何replace???????
让代码输出我想要的? (编辑:我想输出单元格的数值在相应的数组元素的左边一列)
试试这个只是基于你想在你的问题上做什么。
第一种方法是放弃数组并使用Range Objects
。
第二种方法是使用二维数组。
Dim eleOutput As Range, c As Range With Sheets("CHPSpecs") For R = 5 To 145 If .Cells(R, 4).Value >= 0.9 * CHPSize _ And .Cells(R, 4).Value <= 1.1 * CHPSize Then If eleOutput Is Nothing Then Set eleOutput = .Cells(R, 3) Else Set eleOutput = Union(eleOutput, .Cells(R, 3)) End If End If Next R End With For Each c In eleOutput If c.Value <= compareNum Then MsgBox c.Offset(0, 1).Value End If Next
我不知道为什么你需要存储比较值。
在我看来,你可以直接做,如果你只是想显示在这样的MsgBox
的值:
With Sheets("CHPSpecs") For R = 5 To 145 If .Cells(R, 4).Value >= 0.9 * CHPSize _ And .Cells(R, 4).Value <= 1.1 * CHPSize Then If .Cells(R, 3) <= compareNum Then MsgBox .Cells(R, 4).Value2 End If End If Next R End With
另一种方法是通过arrays中的两列创build一个二维数组,像这样:
Dim eleOutput as Variant eleOutput = Sheets("CHPSpecs").Range("C5:D145") For j = LBound(eleOutput, 1) To UBound(eleOutput, 1) If eleOutput(j, 2) >= 0.9 * CHPsize _ And eleOutput(j, 2) <= 1.1 * CHPsize Then If eleOutput(j, 1) <= compatenum Then MsgBox eleOutput(j, 2) End If End If Next
再次,如你所见,我直接做了比较,如果你唯一的目的是显示它。
否则,您将不得不将其转移到另一个数组中,您可以在代码的其他部分使用该数组。
当您在数组eleOutput(j)
中包含的单元格旁边写入单元格时,您不清楚要显示哪个单元格。 我会假定你的意思是每个eleOutput(j)
单元右边的单元格,但如果我的假设不正确,则可能需要进行调整。
最好的方法是将Range
对象存储在数组中,而不是仅存储该Value
。 当您使用Range.Value
来获取单元格的值时,不再有单元格本身的引用。
由于这是较大子程序的一个子集,因此您可能需要对其他地方的eleObject
进行一些调整,或者完全使用新的数组来存储这些Range
对象。
在允许eleObject
存储Range
而不是Range.Value
( Variant
)之后,可以这样做:
j = 0 ' Moved before loop For R = 5 To 145 If Worksheets("CHPSpecs").Cells(R, 4).Value >= 0.9 * CHPSize And Worksheets("CHPSpecs").Cells(R, 4).Value <= 1.1 * CHPSize Then ReDim Preserve eleOutput(j) eleOutput(j) = Worksheets("CHPSpecs").Cells(R, 3) ' Note that .Value has been removed End If Next R For j = LBound(eleOutput) To UBound(eleOutput) If eleOutput(j).Value <= compareNum Then MsgBox Worksheets("CHPSpecs").Cells(eleOutput(j).Row, eleOutput(j).Column + 1).Value ' Assuming cell is one position to the right End If Next j
正如@BranislavKollár的评论中所描述的那样,您正在为此循环的每次迭代分配j = 0
。 相反,你可以在循环开始之前移动j = 0
。 我编辑了我的答案,以显示此作业的新位置。