For-Next有没有更有效的方法,包括If-Then语句?
我正在提高两个macros的效率。 除了标题中描述的方法之外,我已经设法改进了所有的方法。 它是完全function的,但我相信有一个更好的方法来纠正我下面提供的代码的一部分:
For Each cell2 In Range("L2:L" & lastrow2) If Not cell2.Offset(0, -1).Value = 0 Then If cell2.Offset(0, -5).Value = "SOCHACZEW" Then cell2.Value = 31.2 ElseIf cell2.Offset(0, -5).Value = "SEKERPINAR" Then cell2.Value = 33 ElseIf cell2.Offset(0, -5).Value = "ATHENS" Then cell2.Value = 28 ElseIf cell2.Offset(0, -5).Value = "MECHELEN" Then cell2.Value = 33 ElseIf cell2.Offset(0, -5).Value = "TIMISOARA" Then cell2.Value = 34 ElseIf cell2.Offset(0, -5).Value = "STRANCICE" Then cell2.Value = 33 ElseIf cell2.Offset(0, -5).Value = "KLIPPAN" Then cell2.Value = 33 ElseIf cell2.Offset(0, -5).Value = "MATARO" Then cell2.Value = 33 ElseIf cell2.Offset(0, -5).Value = "KIEV" Then cell2.Value = 32 ElseIf cell2.Offset(0, -5).Value = "ROSTOV" Then cell2.Value = 32.6 ElseIf cell2.Offset(0, -5).Value = "ITELLA" Then cell2.Value = 32 End If End If Next cell2
您可以将一些ElseIf
组合在一起,因为它们共享相同的结果,并切换到Select Case
,您的代码可以缩短如下:
For Each cell2 In Range("L2:L" & lastrow2) With cell2 If Not .Offset(0, -1).Value = 0 Then Select Case .Offset(0, -5).Value Case "SOCHACZEW" .Value = 31.2 Case "SEKERPINAR", "MECHELEN", "STRANCICE", "KLIPPAN", "MATARO" .Value = 33 Case "ATHENS" .Value = 28 Case "KIEV", "ITELLA" .Value = 32 Case "ROSTOV" .Value = 32.6 Case "TIMISOARA" .Value = 34 End Select End If End With Next cell2
@ShaiRado答案确实使代码更短,但为了提高性能,您应该使用数组来最小化与范围的交互:
Option Explicit Public Sub SetCities() Const COL_G = 1 Const COL_K = 5 Const COL_L = 6 Dim r As Long, arr As Variant, lastrow2 As Long, ws As Worksheet Set ws = ThisWorkbook.Worksheets("Sheet1") 'read entire range With ws lastrow2 = .Cells(.Rows.Count, "L").End(xlUp).Row arr = .Range("G2:L" & lastrow2) End With For r = 1 To UBound(arr) If Not IsError(arr(r, COL_G)) And Not IsError(arr(r, COL_K)) Then If Len(arr(r, COL_K)) > 0 Then Select Case arr(r, COL_G) Case "SOCHACZEW": arr(r, COL_L) = 31.2 Case "SEKERPINAR", "MECHELEN", "STRANCICE", "KLIPPAN", "MATARO" arr(r, COL_L) = 33 Case "ATHENS": arr(r, COL_L) = 28 Case "TIMISOARA": arr(r, COL_L) = 34 Case "KIEV", "ITELLA" arr(r, COL_L) = 32 Case "ROSTOV": arr(r, COL_L) = 32.6 End Select End If End If Next ws.Range("G2:L" & lastrow2) = arr 'write entire range End Sub
或者至less在执行前closuresApplication.ScreenUpdating
,然后重新执行
您还应完全限定所有范围,以明确工作表