如何处理Excel VBAinputvariables中的破折号?

我有一个Excel VBAmacros的一些麻烦,并希望你可以给我一些build议,如何解决它。 在下面的代码中,当用户点击一个命令button时,popup一个input框,用户input一个XXX-XXXXXX(例如111-222222)forms的数字。 然后,macros从与button相邻的列中获取值,并使用inputvariablesreplace相邻列值的某个部分。 但是,当我试图运行macros并input一个数字,如123-456789,没有任何反应。 我相信这与用户input的短划线有关,但我不知道如何解决这个问题。 请帮忙!

Sub CommandButtonTitleXXXdashXXXXXX_Click() Application.ScreenUpdating = False On Error Resume Next Dim n As Integer n = Worksheets("REVISIONS").Range("D3:D17").Cells.SpecialCells(xlCellTypeConstants).Count If n = 15 Then If MsgBox("Title revision box full. Add manually.", vbOKOnly, "Error") = vbOK Then Exit Sub End If End If Dim rs As Integer rs = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Row Dim amount As String Application.ScreenUpdating = True amount = Application.InputBox("Enter case number:", "") Application.ScreenUpdating = False If amount = False Then Exit Sub Else Dim newCell As String newCell = Replace(Worksheets("TITLE").Range("A" & rs).Value, "XXX-XXXXXX", amount) Worksheets("REVISIONS").Range("D17").End(xlUp).Offset(1, 0) = newCell End If End Sub 

我会把你的代码join一个额外的步骤。

不需要将amount声明为String 。 你可以保持它作为一个Variant 。 也像我在上面的评论中提到的

你的病例号可以像@ D1-1%#456吗? 如果不是那么你有一个额外的问题来处理;)

看到这个例子。 我已经评论了代码,以便您不会理解它。 如果你还是知道的话:)另一种方法是使用REGEX来validation你的案例ID。 让我知道你是否也想要这个例子。

 Sub Sample() Dim amount As Variant ' 123-$456789 <~~ Invalid ' 123-4567890 <~~ Valid ' ABC-&456789 <~~ Invalid ' 456-3456789 <~~ Valid amount = Application.InputBox("Enter case number:", "") '~~> Check if user pressed cancel If amount = False Then Exit Sub '~~> Check if then Case ID is valid If IsValidCaseNo(amount) Then MsgBox amount Else MsgBox "Invalid case ID" End If End Sub Function IsValidCaseNo(sAmount) As Boolean Dim s As String Dim i As Long, j As Long s = sAmount ' '~~> Initial basic checks ' '~~> Check if the length is 11 characters If Len(Trim(s)) <> 11 Then GoTo Whoa '~~> Check if the string contains "-" If InStr(1, s, "-") = 0 Then GoTo Whoa '~~> Check if the 4th character is a "-" If Mid(s, 4, 1) <> "-" Then GoTo Whoa '~~> Loop through 1st 3 characters and check '~~> If they are numbers For i = 1 To 3 Select Case Asc(Mid(s, i, 1)) Case 48 To 57 Case Else: GoTo Whoa End Select Next '~~> Loop through last 6 characters and check '~~> If they are numbers For i = 5 To 11 Select Case Asc(Mid(s, i, 1)) Case 48 To 57 Case Else: GoTo Whoa End Select IsValidCaseNo = True Next Whoa: End Function 

如果你的字符数量为Dim,你可以testing它为一个string:

 Sub GetDash() Dim amount As String amount = Application.InputBox(Prompt:="Enter case number", Type:=2) If amount = "False" Then MsgBox "You cancelled" End If End Sub