简体   繁体   English

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

[英]Error when using a String as Range (VBA Excel)

I am trying to use a string to select some cells by using Range(MaPlage), but this doesn't work. 我正在尝试使用字符串通过使用Range(MaPlage)选择某些单元格,但这不起作用。 Here is the code and how I constructed the string: 这是代码以及如何构造字符串:

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

There is an error at "Range(MaPlage).Select" “ Range(MaPlage).Select”出现错误

I have also tried Set MyRange = Range(MaPlage) but it gives me the same error. 我也尝试了Set MyRange = Range(MaPlage),但它给了我同样的错误。

Excel gives me the error in French but it's something like: "Error 1004: The 'Range' method from the object '_Global' has failed." Excel用法语给出了我该错误,但它类似于:“错误1004:对象'_Global'中的'Range'方法失败。”

Thanks a lot! 非常感谢!

EDIT: I just tried with 编辑:我刚刚尝试

For Line = 1 To 40 Step 1

Instead of 100, and it worked correctly. 而不是100,它可以正常工作。 Does this mean that when the selection goes all the way to line 100 it is to big ? 这是否意味着当选择一直到第100行时就很大了吗?

It would appear maximum address length in Excel is 255 characters. 在Excel中,最大地址长度为255个字符。

However you almost never need to build an address as a string. 但是,您几乎不需要将地址构建为字符串。

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

Depending on the size of the sheet's UsedRange and your needs, you might get away with simply doing 根据工作表的UsedRange的大小和您的需求,您可能会因为简单地

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

but this can raise an error if it doesn't find any cells, and it can cause the SelectionChange event to fire for no reason (Excel bug IMO). 但这会在找不到任何单元格的情况下引发错误,并且可能无缘无故引发SelectionChange事件(Excel错误IMO)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM