复制数组值时“需要对象”的错误

时间:2015-08-17 09:31:28

标签: arrays excel vba excel-vba

我有

的错误消息
  

需要对象

hostname(X, 1).Copy

我已使用msgbox测试此行,并且可以找到此数组的主机名,但只是这行代码有错误消息。此数组值的主机名为W01GOPTIMAPP1A。

相关代码是

wSlastRow = .Range("B" & .Rows.Count).End(xlUp).Row
    hostname = WintelSheet.Range("B1:B" & wSlastRow).Value2
    '// Now Loop through each row
    For X = 2 To wSlastRow

    If Not IsError(.Range("AI" & X).Value) Then
        If IsDate(.Range("AI" & X)) Then

        '//Calculate the last day of the month for dates in Column W (dtStart) and first day of the next current month (dtFinal)
        dtStart = DateSerial(Year(.Range("AI" & X)), Month(.Range("AI" & X)) + 1, 1)
        dtFinal = DateSerial(Year(Now), Month(Now) + 1, 1)
        With AparSheet
        .AutoFilterMode = False
        With .Range("J:L")
        .Columns(3).AutoFilter field:=1, Criteria1:=">=" & dtStart, _
        Operator:=xlAnd, Criteria2:="<" & dtFinal
            With .Resize(.Rows.Count - 1, 1).Offset(1, 0)
            NumberOfPasteRows = .Rows(.Rows.Count).End(xlUp).Row
            If CBool(Application.Subtotal(103, .Columns(1))) Then
                .EntireRow.Copy Destination:=GeneratedSheet.Rows(wSLastPasteRow & ":" & (wSLastPasteRow + NumberOfPasteRows - 1))
                hostname(X, 1).Copy
                GeneratedSheet.Range("B" & wSLastPasteRow).Resize(NumberOfPasteRows - 1).PasteSpecial xlPasteValues
                wSLastPasteRow = wSLastPasteRow + NumberOfPasteRows - 1

            End If
            End With
        End With
        End With
        End If
    End If
    Next X

1 个答案:

答案 0 :(得分:1)

发布的代码不完整但基于行为“hostname”声明为Variant,如果未声明,则为Variant

当您执行此操作hostname = WintelSheet.Range("B1:B" & wSlastRow).Value2时,您将Range对象中的值分配给Variant(数组)

Range对象有一个名为“.Copy”的方法,Variant不是

修改

能够从hostname复制,将其声明为Range对象:

Dim hostname As Range
Set hostname = WintelSheet.Range("B1:B" & wSlastRow)

hostname(x, 1).Copy

或只是使用范围本身:

WintelSheet.Range("B" & wSlastRow).Copy