簡體   English   中英

使用字符串作為范圍時出錯(VBA Excel)

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

我正在嘗試使用字符串通過使用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

“ Range(MaPlage).Select”出現錯誤

我也嘗試了Set MyRange = Range(MaPlage),但它給了我同樣的錯誤。

Excel用法語給出了我該錯誤,但它類似於:“錯誤1004:對象'_Global'中的'Range'方法失敗。”

非常感謝!

編輯:我剛剛嘗試

For Line = 1 To 40 Step 1

而不是100,它可以正常工作。 這是否意味着當選擇一直到第100行時就很大了嗎?

在Excel中,最大地址長度為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)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM