我是VBA的新手。
我遇到了一个问题,我找不到任何使用谷歌的答案。目标是:选择多行,然后删除它们。这是代码:
Dim i As Long
Dim SelectedCells As String
i = 1
SelectedCells = ""
While IsEmpty(Range("A" & i)) = False
If Range("A" & i) < 5 Then
SelectedCells = SelectedCells & i & ":" & i & ","
i = i + 1
Else:
i = i + 1
End If
Wend
SelectedCells = Left(SelectedCells, Len(SelectedCells) - 1)
'That is how I inspected the value of the "SelectedCells" variable:
'Range("AA1").Value = Right(SelectedCells, 25)
Range(SelectedCells).Select
Selection.Delete Shift:=xlUp
最多可选45项。如果需要选择更多,则会在&#34;范围(SelectedCells)返回错误消息。选择&#34;: &#34;运行时错误&#39; 1004&#39;: 方法&#39;范围&#39;对象&#39; _Global&#39;失败。
但是,我检查了SelectedCells变量的值,看起来应该......
有人知道出了什么问题吗?你有什么更好的想法来解决这个问题吗?我需要在数千(或数十万)条记录上运行这种循环。
任何输入都会受到影响。
谢谢。
答案 0 :(得分:0)
删除前无需选择范围。您不必使用单元格地址。
' Get a reference to sheet
Dim s As Worksheet
Set s = ThisWorkbook.Sheets("Sheet1")
' Get reference of range including row n to m
Dim n As Integer
Dim m As Integer
n = 10
m = 29
Dim r As Range
Set r = s.Range (s.Rows (n), s.Rows (m))
r.Delete
答案 1 :(得分:0)
你可以这样做:
Range("10:100").Delete
或
Range(n & ":" & m).Delete
答案 2 :(得分:0)
SelectedCells是一个字符串(最大长度为256),所以它恰好是45个选项。相反,使用如下的循环:
好吧,这会提高你的东西的速度,即使它有点复杂 (PS:不要使用select,除非你想选择作为最终目标) (PS2:代码未经过测试,可根据您的需求进行调整)Dim ColA() as variant 'declares variable of VBA Array (wich is faster than Excel Array)
Dim i as long , MaxData as Long
Dim Sh as Worksheet
With Application
.screenupdating=false
.enableevents=false
.calculation=XlManual
End with
Set Sh = Activesheet 'for multiple sheets just add sh in an argument when calling the macro
with sh
MaxData = .cells( .rows.count , "A").End(Xlup).row 'count the lines in Column A
redim ColA (1 to maxData , 1 to 1)
ColA = .range( .cells(1,1) , .cells( MaxData,1) ).value 'ok, you can write this .range("A1:A" & maxData).value , also
Dim Temp as Variant
For i=MaxData to step -1 'if you go the other way, some lines will be forgotten
temp = ColA(i,1)
if isempty(temp) then
exit for
Elseif Temp<5 then .Cells(i,1).EntireRow.delete 'can be written many other ways, dont use select ; might need a if isnumber(Temp) or if isnumeric(Temp) to avoid text, but i used temp as variant to settle this
'a simple .rows(i).delete , might just do the trick :)
'also an other way : instead of adding the line number (i) to a string , you can increment a variable array ToDelete(1)=line1, Todelelte(2)=line28 ...
'in my example of code i delete right away...
End if
Next i
erase ColA
set sh=nothing
With Application
.screenupdating=true
.enableevents=true
.calculation=XlAutomatic
End with