我正在编写一个VBA问题,该问题找到被认为无效的行,将行号保存在名为invalidRowsToDelete
的数组中,并通过构建无效行的字符串来删除所选行(例如1:1, 4:4, 7:7
)。
但是,它有时会起作用,有时候不会,但是在大量无效行的情况下会更加一致。
它返回的错误是:"运行时错误' 1004':对象的方法范围' _global' Set rng = Range(invalidRowsToDelete)
Public rng As Range
__________________________
Dim invalidRowsToDelete As String
Dim i As Long
For i = LBound(InvalidFilesArr) To UBound(InvalidFilesArr)
If InvalidFilesArr(i) <> "" Then
invalidRowsToDelete = invalidRowsToDelete & InvalidFilesArr(i) & ":" & InvalidFilesArr(i) & ","
Else
Exit For
End If
Next i
'Build range statement and delete trailing comma from rowsToDeleteStatement
invalidRowsToDelete = "" & Left(invalidRowsToDelete, Len(invalidRowsToDelete) - 1) & ""
Debug.Print invalidRowsToDelete
Worksheets("Sheet1").Activate
Set rng = Range(invalidRowsToDelete) #### Problem line
rng.Select
rng.Delete
这已经让我有一段时间了,我无法解决导致此错误的原因。
由于
答案 0 :(得分:2)
使用字符串构建复杂的范围引用通常是个坏主意。我会使用循环来构建范围,而不是描述范围的字符串。
Public rng As Range
__________________________
Dim invalidRowsToDelete As String
Dim i As Long
i = LBound(InvalidFilesArr)
Set rng = Worksheets("Sheet1").Rows(InvalidFilesArr(i))
For i = LBound(InvalidFilesArr) + 1 To UBound(InvalidFilesArr)
If InvalidFilesArr(i) = "" Then
Exit For
End If
Set rng = Union(rng, Worksheets("Sheet1").Rows(InvalidFilesArr(i)))
Next i
rng.Delete
答案 1 :(得分:0)
为什么不删除那里的行,然后找到它们?
Public rng As Range
Dim invalidRowsToDelete As String
Dim i As Long
Worksheets("Sheet1").Activate
For i = LBound(InvalidFilesArr) To UBound(InvalidFilesArr)
If InvalidFilesArr(i) <> "" Then
Set rng = Range(InvalidFilesArr(i) & ":" & InvalidFilesArr(i))
rng.Select
rng.Delete
Else
Exit For
End If
Next i
答案 2 :(得分:0)
你的字符串&#34;糟糕&#34;; 找出替换的原因:
Set rng = Range(invalidRowsToDelete)
使用:
On Error GoTo GhostBusters
Set Rng = Range(invalidRowsToDelete)
并且在sub的底部包括:
GhostBusters:
MsgBox Len(invalidRowsToDelete)
MsgBox invalidRowsToDelete
On Error GoTo 0
答案 3 :(得分:0)
使用Union
获取要删除的范围,然后在此范围内调用Delete
。 HTH
Dim rngToDelete As Range
Dim rngRow As Range
Dim rowsToDelete(0 To 5) As Long
Dim i As Long
rowsToDelete(0) = 2
rowsToDelete(1) = 5
rowsToDelete(2) = 7
rowsToDelete(3) = 9
rowsToDelete(4) = 10
rowsToDelete(5) = 12
For i = LBound(rowsToDelete) To UBound(rowsToDelete)
Set rngRow = ActiveSheet.Rows(rowsToDelete(i))
If rngToDelete Is Nothing Then
Set rngToDelete = rngRow
Else
Set rngToDelete = Application.Union(rngToDelete, rngRow)
End If
Next i
if Not rngToDelete Is Nothing Then rngToDelete.Delete