Excel 如果语句和输入框选中“验证用户输入”
我有一个代码,要求用户通过在输入框中写入图纸名称来选择图纸,然后我需要检查所选名称是否正确 如何编写if语句以返回到inputbox 我在Windows7中使用MS Word。代码如下:Excel 如果语句和输入框选中“验证用户输入”,excel,vba,if-statement,inputbox,Excel,Vba,If Statement,Inputbox,我有一个代码,要求用户通过在输入框中写入图纸名称来选择图纸,然后我需要检查所选名称是否正确 如何编写if语句以返回到inputbox 我在Windows7中使用MS Word。代码如下: Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1) End Function 如果替换以uiS
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
如果替换以uiSheet=InputBox开头的代码。。。。。使用下面的代码,它应该可以工作
'check if User input match with sheet name
Dim bSheetPresent As Boolean
bSheetPresent = False
Do Until bSheetPresent
uiSheet = InputBox("Provide a sheet name." & vbNewLine & strBuild)
If uiSheet = "" Then Exit Do
If IsInArray(uiSheet, myArray) Then
bSheetPresent = True
Else
MsgBox "Please enter a valid name!", vbCritical
End If
Loop
If bSheetPresent Then
'show excel window
oExcel.visible = True
'sort selected sheet by first column range
oExcel.Worksheets(uiSheet).Activate
Set oneRange = oExcel.Range("A1:A150")
Set aCell = oExcel.Range("A1")
oneRange.Sort Key1:=aCell, Order1:=xlAscending, Header:=xlYes
End If
如果用户在inputbox上按cancel,则它将退出循环
<>你也可以考虑用预填充的组合框来构建一个表单。这样用户就不会出错。要创建自己的带有工作表列表的输入框,可以执行以下操作: 在VBE中创建用户窗体 将其命名为frmSelectSheet 在上面放一个名为cbSheets的组合框 将以下代码添加到userform的“代码”窗格:
Private Sub UserForm_Initialize()
Dim oSheet As Worksheet
For Each oSheet In ThisWorkbook.Sheets
Me.cbSheets.AddItem oSheet.Name
Next oSheet
End Sub
Private Sub cbSheets_Change()
Me.Hide
End Sub
添加模块并向其添加以下代码:
Public Function SheetInputBox() As String
Dim ofrmSheetInput As New frmSelectSheet
ofrmSheetInput.Show
SheetInputBox = ofrmSheetInput.cbSheets
Unload ofrmSheetInput
End Function
像这样调用函数
??SheetInputBox或uiSheet=SheetInputBox如果要执行循环语句,将输入框作为循环中的第一行,请使用if语句检查是否有效,如果有效,请退出循环。如果无效,则循环。谢谢,我可以用数组值而不是InputBox创建组合框吗?我不知道怎么做你应该创建你自己的用户表单,并调用它而不是inputbox。如果你愿意的话,我可以写一个例子,循环代码工作得很好,我尝试使用组合框,但不起作用:全局对象的ThisWorkBook方法失败。我想是因为我们在MS WordCombo框中工作,但不工作:全局对象的ThisWorkBook方法失败。ofrmSheetInput。突出显示显示。我想是因为我们在微软工作
Public Function SheetInputBox() As String
Dim ofrmSheetInput As New frmSelectSheet
ofrmSheetInput.Show
SheetInputBox = ofrmSheetInput.cbSheets
Unload ofrmSheetInput
End Function