在VBA中debugging“search名称”代码

我在C ++方面有丰富的经验,但是我仍然习惯于VBA的语法,我认为这就是我在代码中绊倒我的原因。

我想要做的是有一个button,要求用户的名字。 如果input的名字在列B中,那么告诉用户名字被find并且select它在哪里(没有问题)。 如果找不到名字,那么询问用户是否想尝试另一个名字(对此也没有问题)。

我遇到麻烦的地方是“取消”button。 在任何时候,我希望用户能够点击“取消”并立即停止循环,但留在子,因为我会在稍后添加。

代码如下:

Dim inputName As String Dim row As Integer Dim i As Integer Dim tryAgainResponse As Integer tryAgainResponse = vbOK 'Ask user for name they would like to replace' inputName = InputBox("What is the name of the person you would like to find? (First Last)") 'Find the row that the name is located and tell the user where it is' Do While tryAgainResponse = vbOK For i = 1 To 1000 If Cells(i, 2).Value = inputName Then MsgBox ("Found the name! It's located at cell B" & i & ".") ActiveSheet.Cells(i, 2).Select tryAgainResponse = 0 Exit Do End If Next i tryAgainResponse = MsgBox("We didn't find the name you were looking for. Please try again.", vbOKCancel) If tryAgainResponse = vbCancel Then Exit Do End If inputName = InputBox("What is the name of the person you would like to find? (First Last)") Loop 

我已经尝试了很多东西,但主要的错误是当你打开第一个MsgBox的取消时,它会告诉你在第一个空白的方块中find了这个名字。

任何帮助或build议将不胜感激! 这是我的第一个VBA程序,所以它不是最漂亮的,但它绝对是很有趣的。 谢谢!

我不知道我是否理解你要求的内容,我不能澄清,但我认为你的挂断是当你点击INPUT框中的取消,你的input框返回一个空白string,然后你的代码的其余部分,然后find一个空白单元格。

使用Application.Input方法,将inputstring声明为变体,并testing它是否为假。 如果是,请使用Exit Sub退出macros。 您也可以testing您的inputstring=“”,然后退出macros,如果您的代码为真。

来自MrExcel

在VBA中有两个版本的InputBox。

InputBox函数在没有对象限定符的情况下调用,如果用户单击Cancel,则返回文本框的内容或零长度string(“”)。

InputBox方法是Application对象的成员,所以它通过使用Application.InputBox进行调用。 它返回文本框的内容,如果用户点击取消,则返回False。 它比InputBox函数更通用,因为它有一个指定返回数据types的Type参数。

如果取消,函数InputBox()将返回一个空string。 空string将与第一个空单元格相比较。

这是该函数的文档: http : //msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx