输入框做,直到两个字母被输入(Inputbox do until two letters are e

2019-10-18 11:15发布

这是我第一次用的InputBox工作。 的愿望是让用户插入它们的缩写为进入将被导入到数据库中的电子表格。 我使用的InputBox促进一致性和自动填充所需的细胞。

我无法理解一个过程,由此用户输入的信息,如果该条目是两个字母其接受并填充到细胞中,否则将出现一条消息,指示两个字母是必需的,所述的InputBox再次显示。 通过测试,我相信我的回路不工作,我期望的那样。 如果第一项是两个字母它的信息填充到Excel预期。 但是,如果第一项是不正确的,随后的条目是正确的它似乎并没有退出循环。 我不知道为什么会是什么? 任何帮助将不胜感激。

Dim c As Range

Set c = Sheets("CompilePriceAdjustments").Range("E2")

    c = InputBox("Please Enter Initials", "PRICE INCREASE APPROVER")
Do Until c = vbString And Len(c) = 2
    MsgBox ("You must enter two letters")
    c = InputBox("Please Enter Initials", "PRICE INCREASE APPROVER")
Loop

Sheets("CompilePriceAdjustments").Range("E2").Value = UCase(c)
c.AutoFill Destination:=Sheets("CompilePriceAdjustments").Range("E2:E" & Cells    (Rows.Count, "D").End(xlUp).Row)

Answer 1:

我觉得这是你想什么呢?

Sub Sample()
    Dim c As Range
    Dim Ret

    Set c = Sheets("CompilePriceAdjustments").Range("E2")

    Ret = InputBox("Please Enter Initials - (Only alphabets allowed of 2 Length)", "PRICE INCREASE APPROVER")

    Do Until (isString(Ret) And Len(Ret) = 2)
        Ret = InputBox("Please Enter Initials - (Only alphabets allowed of 2 Length)", "PRICE INCREASE APPROVER")
    Loop

    c.Value = UCase(Ret)
    '
    '~~> Rest of the code
    '
End Sub

Function isString(s As Variant) As Boolean
    Dim i As Long

    isString = True

    For i = 1 To Len(s)
        Select Case Asc(Mid(s, i, 1))
        Case 65 To 90, 97 To 122
        Case Else
            isString = False
            Exit Function
        End Select
    Next i
End Function

编辑

我看到你的方法有一个漏洞。 如果有什么要取消并退出? 你可能要考虑这个代码?

Sub Sample()
    Dim c As Range
    Dim Ret

    Set c = Sheets("CompilePriceAdjustments").Range("E2")

    Ret = InputBox("Please Enter Initials-(Only alphabets allowed of 2 Length)", _
          "PRICE INCREASE APPROVER")

    '~~> Added  Or Ret = "" so that user can cancel the inputbox if required
    Do Until (isString(Ret) And Len(Ret) = 2) Or Ret = ""
        Ret = InputBox("Please Enter Initials-(Only alphabets allowed of 2 Length)", _
        "PRICE INCREASE APPROVER")
    Loop

    '~~> This is required so that user can press cancel and exit
    If Ret = "" Then Exit Sub

    c.Value = UCase(Ret)
    '
    '~~> Rest of the code
    '
End Sub

Function isString(s As Variant) As Boolean
    Dim i As Long

    isString = True

    For i = 1 To Len(s)
        Select Case Asc(Mid(s, i, 1))
        Case 65 To 90, 97 To 122
        Case Else
            isString = False
            Exit Function
        End Select
    Next i
End Function


Answer 2:

考虑:

Sub dural()
    Dim c As Range, init As String
    Set c = Sheets("CompilePriceAdjustments").Range("E2")
    init = ""
    While Len(init) <> 2
        init = Application.InputBox(Prompt:="Enter two initials", Type:=2)
    Wend
    MsgBox "Thanks"
    c.Value = init
End Sub


文章来源: Inputbox do until two letters are entered