长度限制在VBA范围内

时间:2019-03-21 17:18:35

标签: excel vba

我还是VBA的新手,并试图创建VBA代码,在该代码中,用户在每个指定的列中都被限制为某些字符长度。如果字符长度较大,则会显示一条错误消息。该代码从B列第10行开始,具体取决于用户输入数据的行数。我不确定出什么问题了,因为我已经尝试调试了一段时间,但是没有运气。下面是我的代码,希望有人能帮助我弄清楚我做错了什么。谢谢!

Sub LenValid()
Dim sht     As Worksheet
Dim wrk     As Workbook
Dim lrow    As Long
Dim rng1    As Range
Dim rng2    As Range
Dim i       As Integer
Dim finprod As Variant
Dim subprod As Variant

Set wrk = ActiveWorkbook
Set sht = wrk.Worksheets(1)

For Each sht In wrk.Worksheets

    lrow = sht.Range("B" & Rows.Count).End(xlUp).Row
    Set rng1 = sht.Range("B10:B" & lrow) 'CUSTOMER ACCT
    Set rng2 = sht.Range("C10:C" & lrow) 'CUSTOMER NAME
    i = 1
    For i = 10 To lrow

        If Len(rng1.Range("A" & i).Value) > 15 Then
            MsgBox "Customer Acct limited to 15 characters." & vbNewLine & "Please review and correct.", vbExclamation
            Exit Sub
        End If

        If Len(rng2.Range("B" & i).Value) > 10 Then
            MsgBox "Customer Name limited to 10 characters." & vbNewLine & "Please review and correct.", vbExclamation
            Exit Sub
        End If

    Next i    
Next sht

'Error Handler
NothingFound:
MsgBox "Character length in required fields are valid.", vbInformation
End Sub

1 个答案:

答案 0 :(得分:0)

尝试一下。找到长文本后,该代码仍将退出,但至少应显示消息框。

Sub LenValid()

Dim sht As Worksheet
Dim wrk As Workbook
Dim lrow As Long
Dim rng1 As Range
Dim rng2 As Range
Dim i As Long
Dim finprod As Variant
Dim subprod As Variant

Set wrk = ActiveWorkbook

For Each sht In wrk.Worksheets
    lrow = sht.Range("B" & Rows.Count).End(xlUp).Row
    Set rng1 = sht.Range("B10:B" & lrow) 'CUSTOMER ACCT
    Set rng2 = sht.Range("C10:C" & lrow) 'CUSTOMER NAME
    For i = 1 To rng1.Count
        If Len(rng1.Cells(i).Value) > 15 Then
            MsgBox "Customer Acct limited to 15 characters." & vbNewLine & "Please review and correct.", vbExclamation
            Exit Sub
        End If
        If Len(rng2.Cells(i).Value) > 10 Then
            MsgBox "Customer Name limited to 10 characters." & vbNewLine & "Please review and correct.", vbExclamation
            Exit Sub
        End If
    Next i
Next sht

'Error Handler
NothingFound:
MsgBox "Character length in required fields are valid.", vbInformation

End Sub

您的问题可能是这个:

Set rng1 = sht.Range("B10:B" & lrow) If Len(rng1.Range("A" & i).Value) > 15 Then

如果i=10正在检查rng1中的第10个像元,则它是相对的,即它从B20开始。