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

时间:2015-06-29 08:40:45

标签: string excel vba range

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

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

&#34;范围(MaPlage)出现错误。选择&#34;

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

Excel用法语给出了错误,但它类似于:&#34;错误1004:&#39;范围&#39;来自对象&#39; _Global&#39;的方法失败了。&#34;

非常感谢!

编辑:我刚试过

For Line = 1 To 40 Step 1

而不是100,它正常工作。这是否意味着当选择一直到第100行时它会变大?

1 个答案:

答案 0 :(得分:1)

它会显示http://myapp.com/publication/1个字符。

但是您maximum address length in Excel is 255要将地址构建为字符串。

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

根据工作表的大小UsedRange以及您的需求,您可以轻松完成

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

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