Excel VBA将单个值拉出范围并放入单元格

时间:2016-05-04 07:56:52

标签: arrays excel vba excel-vba

以下代码有时有效,有时则无效:

Sub anothertest()
    Dim vArray As Variant
    Dim x As Integer
    Dim y As String
    'vArray = Array("Cat", "Dog", "Rabbit")
    With ActiveSheet
        vArray = Range("G2:G10").Value
    End With
    x = UBound(vArray) - LBound(vArray) + 1
    MsgBox x
    y = vArray(1)
    MsgBox y
    Cells(1, 10).Value = y
End Sub

适用于vArray = Array("Cat", "Dog", "Rabbit")x3yDog
但是,如果我对此进行评论并激活With ActivesheetEnd With,则会正确地将x作为9返回,但会返回Runtime error 9, script out of range,即使它会打印出来的for each for each循环中正确的全范围 我需要sub来使用range参数。它在我的脚本的其他地方完美地工作,我使用<div class="full"> <a class="button" onclick="ChoseEvent(13362,'Whole Match',false)">Match</a> <a class="button" onclick="ChoseEvent(13392,'1st Game','1462327200')">1st Game</a> <a class="button" onclick="ChoseEvent(13424,'2nd Game','1462327200')">2nd Game</a> <br><div id="toma" class="full" style="background: #444;line-height: 2.5rem;border: 1px solid #333;text-align: center;">Whole Match</div> </div> 循环,但在这里我需要从每张纸的范围中选择一个值。此外,我很好奇为什么它不起作用,如果我再次遇到问题。

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

 Sub anothertest()
     Dim vArray() As Variant
     Dim x As Integer
     Dim y As Variant
     With ActiveSheet
        vArray = Application.WorksheetFunction.Transpose(Range("G2:G10").Value) 
     End With
     x = UBound(vArray) - LBound(vArray) + 1
     MsgBox x
     y = vArray(1)
     MsgBox y
     Cells(1, 10).Value = y
 End Sub