这是我第一次使用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)
答案 0 :(得分:2)
我认为这是你在尝试的?
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
答案 1 :(得分:0)
考虑:
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