2017-11-10 133 views
1

我一直在拼凑一个功能工作簿,使用VBA代码,因为我去。通过VLookup提高macor效率?

我目前有一个创建它查看列中的动态值范围,并将它们转换为新值。

Sub ConvertWireSize() 
Dim i As Long 
Sheets("Circuits").Select 
Range("H1").Select 
For i = 1 To Rows.Count 
    If Cells(i, 8).Value = 0.5 Then 
     Cells(i, 8).Value = 20 
    ElseIf Cells(i, 8).Value = 0.8 Then 
     Cells(i, 8).Value = 18 
    ElseIf Cells(i, 8).Value = 1 Then 
     Cells(i, 8).Value = 16 
    ElseIf Cells(i, 8).Value = 2 Then 
     Cells(i, 8).Value = 14 
    ElseIf Cells(i, 8).Value = 3 Then 
     Cells(i, 8).Value = 12 
    ElseIf Cells(i, 8).Value = 5 Then 
     Cells(i, 8).Value = 10 
    ElseIf Cells(i, 8).Value = 8 Then 
     Cells(i, 8).Value = 8 
    ElseIf Cells(i, 8).Value = 13 Then 
     Cells(i, 8).Value = 6 
    ElseIf Cells(i, 8).Value = 19 Then 
     Cells(i, 8).Value = 4 
     End If 
Next i 

MsgBox "Wire Size Has Been Converted From CSA to AWG." 

Sheets("Main").Select 

End Sub 

这似乎是一种非常低效且缓慢的做事方式。 我一直在拼凑一个新的宏,它会使用VLookup,但我做的研究越多,我就越困惑。

有人能帮我指出正确的方向吗?

回答

1

不要转到行1048576,只要列H中的值扩展。使用Select Case来清理您的IF。 Don't use Select

Sub ConvertWireSize() 
    Dim i As Long 
    with workSheets("Circuits") 
     For i = 1 To .cells(.Rows.Count, "H").end(xlup).row 
      select case .Cells(i, 8).Value2 
       case 0.5 
        .Cells(i, 8).Value = 20 
       case 0.8 
        .Cells(i, 8).Value = 18 
       case 1 
        .Cells(i, 8).Value = 16 
       ... 
      end select 
     Next i 
    end with 

    MsgBox "Wire Size Has Been Converted From CSA to AWG." 

    workSheets("Main").Select 
End Sub 

我无法确定转换的线性模式,但您可能可以调整一些数学来完成每次转换。

如果你有超过几千个这样的转换,那么内存数组会显示效率的显着提高。

+0

非常感谢。这大大提高了宏执行的速度。 –