使用字符串作为范围时出错 (VBA Excel)

Error when using a String as Range (VBA Excel)

我正在尝试通过使用 Range(MaPlage) 将字符串用于 select 一些单元格,但这不起作用。这是代码以及我如何构建字符串:

Dim MaPlage As String
Dim MyRange As Range
Dim Line As Integer
Dim AdrRD as String
Dim First_Cell As Boolean

First_Cell = True
AdrRD = "A"

For Line = 1 To 100 Step 1
If Sheet.Range(AdrRD & Line).Value = "" Then
    If First_Cell = True Then
        MaPlage = AdrRD & Line
        First_Cell = False
    Else
        MaPlage = MaPlage & ", " & AdrRD & Line
    End If
End If

Next Line

If MaPlage <> "" Then   
    Range(MaPlage).Select
    Selection.EntireRow.Delete
End If

"Range(MaPlage).Select"

处出现错误

我也试过 Set MyRange = Range(MaPlage) 但它给了我同样的错误。

Excel 给我法语错误,但它类似于:"Error 1004: The 'Range' method from the object '_Global' has failed."

非常感谢!

编辑:我刚试过

For Line = 1 To 40 Step 1

而不是 100,并且它工作正常。这是否意味着当 selection 一直到第 100 行时它太大了?

会出现maximum address length in Excel is 255个字符。

但是你 almost never need 将地址构建为字符串。

Dim MyRange As Range
Dim c As Range
Dim Line As Long

For Line = 1 To 100
  Set c = Sheet.Cells(Line, "A")
  If Len(c.Value) = 0 Then
    If MyRange Is Nothing Then
        Set MyRange = c
    Else
        Set MyRange = Application.Union(MyRange, c)
    End If
  End If
Next

MyRange.EntireRow.Delete

根据 sheet 的 UsedRange 大小和您的需要,您可能只需执行

Sheet.Range("A1:A100").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

但是如果找不到任何单元格,这可能会引发错误,并且可能会导致 SelectionChange 事件无缘无故地触发(Excel IMO 错误)。