代码正常工作-没有更改,现在不正常(VBA)

时间:2019-03-26 06:26:48

标签: excel vba

我很困惑-此代码工作正常-现在,它在错误的列中工作。以L列为例,它被编码为将所选单元格转换为Propercase,但现在它转换为大写。第I列代码被完全忽略。

Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Cleanup
Application.EnableEvents = False: Application.ScreenUpdating = False: Application.Calculation = xlCalculationManual

   'converts staff codes into uppercase
   If Not (Application.Intersect(Target, Me.UsedRange.Columns("K")) Is Nothing) And Not Target.Row = 15 Then
        Target.Value2 = UCase$(Target.Value2)
   End If

   'converts Rep Codes into uppercase
     If Not (Application.Intersect(Target, Me.UsedRange.Columns("J")) Is Nothing) And Not Target.Row = 15 Then
        Target.Value2 = UCase$(Target.Value2)
   End If

   'converts Staff Names into proper case,
   If Not (Application.Intersect(Target, Me.UsedRange.Columns("L")) Is Nothing) And Not Target.Row = 15 Then
        Target.Value2 = StrConv(Target.Value2, vbProperCase)
   End If

   'converts staff type into capitals.
   If Not (Application.Intersect(Target, Me.UsedRange.Columns("I")) Is Nothing) And Not Target.Row = 15 Then
         Target.Value2 = UCase$(Target.Value2)
   End If

   'converts store code into uppercase
    If Not (Application.Intersect(Target, Range("STORE_CODE")) Is Nothing) Then
        Target.Value2 = UCase$(Target.Value2)
   End If

      'converts store name into propercase
   If Not (Application.Intersect(Target, Range("STORE_NAME")) Is Nothing) Then
        Target.Value2 = StrConv(Target.Value2, vbProperCase)
   End If

   'copy pay value one cell over into hidden column
   If Not (Application.Intersect(Target, Me.UsedRange.Columns("G")) Is Nothing) Then
          Target.Offset(0, 1).Value2 = Target.Value2
          Target.Value2 = ""
   End If
Cleanup:
Application.EnableEvents = True: Application.ScreenUpdating = True: Application.Calculation = xlCalculationAutomatic ' etc..
End Sub

1 个答案:

答案 0 :(得分:2)

您代码中的Me.UsedRange.Columns("L")表示第L,即UsedRange的第十二列。如果UsedRange从列A开始,则这是列L。但是,如果UsedRange从列B开始,那么UsedRange的第十二列就是列M

示例:

Sub test()
 Dim oRange As Range

 Set oRange = ActiveSheet.Range("A1:Z100")
 MsgBox oRange.Columns("L").Address 'L1:L100

 Set oRange = ActiveSheet.Range("B1:Z100")
 MsgBox oRange.Columns("L").Address 'M1:M100

End Sub

为什么在您的代码中使用UsedRange