【问题标题】:Excel: "object variable or with block variable not set"Excel:“对象变量或未设置块变量”
【发布时间】:2021-06-01 17:36:07
【问题描述】:

任何想法为什么我在myrange.Copy 行收到此错误?

谢谢

Sub nsort()
Dim wb As Workbook, ws As Worksheet, myrange As Range

Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
Set range_i = Nothing
counter = 0

'Find last row TrE = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

'Start loop assuming data starts in row 2 and 13 columns wide as in example

For Tr = 2 To TrE

If Not myrange Is Nothing Then
    If ws.Cells(Tr, 13) = 0 Then
        Set myrange = Union(myrange, Range(ws.Cells(Tr, 1), ws.Cells(Tr, 13)))
        counter = counter + 1
    End If
Else
    If ws.Cells(Tr, 13) = 0 Then
        Set myrange = Range(ws.Cells(Tr, 1), ws.Cells(Tr, 13))
        counter = counter + 1
    End If
End If

If Not range_i Is Nothing Then
    If ws.Cells(Tr, 13) > 0 Then
        Set range_i = Union(range_i, Range(ws.Cells(Tr, 1), ws.Cells(Tr, 13)))
    End If
Else
    If ws.Cells(Tr, 13) > 0 Then
        Set range_i = Range(ws.Cells(Tr, 1), ws.Cells(Tr, 13))
    End If
End If
Next Tr

Sheets.Add.Name = "summary"

Set Tws = wb.Sheets("summary")

myrange.Copy

Tws.Range("A1").PasteSpecial

range_i.Copy

Tws.Range(Cells(1 + counter, 1), Cells(1 + counter, 13)).PasteSpecial
End Sub

【问题讨论】:

  • 你的循环实际上并没有运行,因为你从来没有给TrE赋值(你注释掉了这样做的行:TrE = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row应该在它自己的行上

标签: excel vba


【解决方案1】:

除了 Rory 的评论以激活以下行

TrE = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

所以你的循环完全被执行了,我建议你稍微优化你的代码块,这样它就不会重复了:

If Not myrange Is Nothing Then
    If ws.Cells(Tr, 13) = 0 Then
        Set myrange = Union(myrange, Range(ws.Cells(Tr, 1), ws.Cells(Tr, 13)))
        counter = counter + 1
    End If
Else
    If ws.Cells(Tr, 13) = 0 Then
        Set myrange = Range(ws.Cells(Tr, 1), ws.Cells(Tr, 13))
        counter = counter + 1
    End If
End If

可以写成

If ws.Cells(Tr, 13) = 0 Then
    If Not myrange Is Nothing Then
        Set myrange = Union(myrange, Range(ws.Cells(Tr, 1), ws.Cells(Tr, 13)))
    Else
        Set myrange = Range(ws.Cells(Tr, 1), ws.Cells(Tr, 13))
    End If
    counter = counter + 1
End If

第二个If 块也可以这样做。

【讨论】:

  • 非常感谢!! :-) 我已将其纳入其中,非常感谢您提出建议。如果您有兴趣再看一下,我还在这里发布了一个新的后续问题? stackoverflow.com/questions/67803569/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
相关资源
最近更新 更多