检查对象是否为null但仍然出错

时间:2014-09-19 12:34:38

标签: excel-vba object range vba excel

嗨我有一个有效的Range对象,但我得到了对象需要的错误

Dim row As Integer
Dim col As Integer
If Not rng Is Nothing Then
   row = rng.row
   col = rng.Column
End If

它进入但是在(Set row = rng.row)行

得到错误

整个代码是这样的:

Dim str() As String
str = GetArray(ActiveSheet.Range("A3"))
Dim element As Variant
Dim rng As Range
Set rng = Range("D3")
For Each element In str
With ActiveSheet.QueryTables.Add(Connection:= _
     element, _
     Destination:=rng)
    .Name = "technicals_1"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .WebSelectionType = xlAllTables
    .WebFormatting = xlWebFormattingNone
    .WebPreFormattedTextToColumns = True
    .WebConsecutiveDelimitersAsOne = True
    .WebSingleBlockTextImport = False
    .WebDisableDateRecognition = False
    .WebDisableRedirections = False
    .Refresh BackgroundQuery:=False
End With
Range(Cells(rng.row, rng.Column), Cells(rng.row + 70, rng.Column + 1)).Select
Selection.Copy
rng.Offset(0, 2).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
    False, transpose:=True
Range(Cells(rng.row, rng.Column), Cells(rng.row + 70, rng.Column + 1)).Select
Selection.QueryTable.Delete
Selection.Delete Shift:=xlToLeft
/* AFTER THIS LINE I GET OBJECT REQUIRED ERROR */
Range(Cells(rng.row, rng.Column), Cells(rng.row, rng.Column + 70)).Select
Selection.Delete Shift:=xlUp
Set rng = rng.Offset(1, 0)
Next element

End Sub

我已编辑过,请再次阅读 请阅读我输入此评论的部分:

/ *在此行之后我获得了对象所需的错误* /

我该怎么办? 感谢

1 个答案:

答案 0 :(得分:0)

每次删除范围时,都必须重新定义范围。

最好不使用范围变量,而是使用具有单元格D3坐标的cells属性(即Cells(3,4))。

因此,要解决问题,请插入

Set rng = Range("D3")  

在给出错误的行之前,然后在下一个Range(...)之后再次。删除语句或不使用范围变量(因为你只是使用了行和对象的列属性)并将rng.Column和rng.Row替换为定义为正确的行号和列号的变量。