为什么在尝试使用VBA循环时味精盒无法正常工作

时间:2019-05-28 20:15:41

标签: vba

我正在尝试运行一个循环,以测试一列中的字符串长度是否至少有十个字符。我调试了,没有问题。但是,我用少于10个字符的字符串进行了测试,不会弹出msg框。我是VBA的新手,所以任何人都可以指出我的问题是什么?非常感谢。

Sub MsgBoxforLenLessThanTen()

    Dim wsData As Worksheet
    Set wsData = Worksheets("Sheet1")
    lastRow = ActiveSheet.UsedRange.Rows.count

    Dim i As Integer
    Dim length As Integer

    i = 1
    With wsData.Range("A1:A" & lastRow)
        Do Until i > lastRow
            length = Len(Range("A1").Offset(0, 1))
            If length < 10 Then MsgBox "not enough characters"
            i = i + 1
            Loop
    End With

End Sub

1 个答案:

答案 0 :(得分:2)

请在下面查看更正后的代码,但请检查“ A”列。查看评论以获取更多详细信息:

datetime

编辑:将msgbox的输出改为B列。我建议您阅读有关Immediate WindowLocals Window的内容,它们对调试代码有很大帮助,尤其是在您逐步完成(Option Explicit 'always use this, it will enforce you to declare your variables, which is well.. important. Sub MsgBoxforLenLessThanTen() Dim wsData As Worksheet Set wsData = Worksheets("Sheet1") Dim lastRow As Long 'Declare your variable lastRow = wsData.UsedRange.Rows.Count 'You've declared your variable above for the sheet, use it Dim i As Integer Dim length As Integer Dim msgValue As String: msgValue = "Not enough characters" 'try the for loop, is much easier With wsData For i = 1 To lastRow length = Len(.Cells(i, "A")) If length < 10 Then 'MsgBox msgValue 'Debug.Print msgValue & " at: " & .Cells(i, "A").Address .Cells(i, "B").Value = msgValue Else 'do something else End If Next i End With End Sub )时。