Excel VBA将数字赋予指定的单元格,避免选择

时间:2018-11-19 09:02:13

标签: excel vba excel-vba optimization

我在Excel中有以下VBA代码。它是非常长的VBA的一部分,负责许多过程。如何摆脱Select命令?我已经尝试了几项没有成功的事情。

ActiveWorkbook.Sheets("Installation").Select
    For Each Cl14 In ThisWorkbook.Sheets("Installation").Range("G2", Range("G" & Rows.Count).End(xlUp))
      Select Case LCase(Cl14.Value)
         Case "main"
            m14 = m14 + 1: s14 = 0: ss14 = 0
            Cl14.Offset(, -6).Value = m14
         Case "sub"
            s14 = s14 + 1: ss14 = 0
            Cl14.Offset(, -6) = m14 & "." & s14
         Case "sub-sub"
            ss14 = ss14 + 1
            Cl14.Offset(, -6) = m14 & "." & s14 & "." & ss14
      End Select
   Next Cl14

2 个答案:

答案 0 :(得分:0)

使用With语句包装Range对象。考虑用更有意义的名称替换变量名。我只换了一个。另外,在代码顶部使用Option Explici t并声明所有类型的变量。

Option Explicit
Public Sub test()
    Dim ws As Worksheet, iCell As Range, m14 As Long, s14 As Long, ss14 As Long
    Set ws = ThisWorkbook.Worksheets("Installation")

    With ws
        For Each iCell In .Range("G2", .Range("G" & .Rows.Count).End(xlUp))
            Select Case LCase(iCell.Value)
            Case "main"
                m14 = m14 + 1: s14 = 0: ss14 = 0
                iCell.Offset(, -6).Value = m14
            Case "sub"
                s14 = s14 + 1: ss14 = 0
                iCell.Offset(, -6) = m14 & "." & s14
            Case "sub-sub"
                ss14 = ss14 + 1
                iCell.Offset(, -6) = m14 & "." & s14 & "." & ss14
            End Select
        Next iCell
    End With
End Sub

答案 1 :(得分:0)

可以进行强制循环以防止选择情况。但是我个人更喜欢使用select case。

For i = 2 To .Range("G" & .Rows.Count).End(xlUp).Row
If .Range("G" & i).Value = "main" Then
'code here
ElseIf .Range("G" & i).Value = "sub" Then
'code here
ElseIf .Range("G" & i).Value = "sub-sub" Then
'code here
End If
Next i