excelvba运行时间错误91对象变量未设置

excel vba run time error 91 object variable not set

不知道什么变量还没有设置

Option Explicit
Option Base 1

Sub ReverseOrder()
    Dim ReverseOrder As Variant
    Dim nEmployee As String
    Dim nEmployees As Integer
    Dim ssn As Variant
    Dim wsData As Range
    Dim i As Integer


    With wsData.Range("A1")
        nEmployees = Range(.Offset(1, 0), .End(xlDown)).Rows.Count
        ReDim Employees(1 To nEmployees)
        ReDim ssn(1 To nEmployees)

        For i = 1 To nEmployees
            Employees(i) = .Offset(i, 0).Value
            ssn(i) = .Offset(i, 0).Value
        Next

        For i = nEmployees To 1 Step -1
            .Offset(nEmployees - i + 1, 3).Value = Employees(i)
            .Offset(nEmployees - i + 1, 4).Value = ssn(i)
        Next i
    End With
End Sub

未设置WsData范围,因此出现91错误。它应该被设置为一些东西,例如:

Set WsData = Worksheets(1).Range("A1")

然后With wsData就可以了

无论如何,考虑到 wsData 名称可能是一个工作表,那么这应该没问题:

Dim wsData As Worksheet
Set wsData = Worksheets(1)

With wsData.Range("A1")

你调暗了 wsData 但没有将其设置为任何对象(例如 Set wsData = Range("A1:A10")

但我觉得wsData应该是一个Worksheet对象

所以

Dim wsData As Worksheet

Set wsData = Worksheets("myWorksheetName") ' change "myWorksheetName" to wanted actual sheet name

然后是你的代码