2016-09-04 4 views
0

VBAが新しくなりました。 msgboxの値とテキストボックスの値を比較するプログラムをVBAで作成しましたが、結果は正しくありません。私は以下のコードをコピーしました。私はこれについて間違って何をしましたか?私を助けてください。msgboxとvbaのテキストボックスとの比較中にエラーが発生しました

あなたが InpoutBoxTextBoxから取得しているすべての値が数字(私のコードでは念のために、 ロングに変換)していることを確認する必要があり
Private Sub CommandButton1_Click() 

    Dim num As String 
    num = Application.InputBox("enter num") 
    If TextBox1.Value * num > TextBox2.Value Then 
     MsgBox "textbox1 is higher" 
    Else 
     MsgBox "textbox2 is higher"  
    End If 

End Sub 
+0

の代わりにVal(TextBox1.Value)を使用していたことを意味する、あなたは右、2 'TextBox'sと' InputBox'を比較しようとしていますか?その場合は、私の答えは –

答えて

0

Private Sub CommandButton1_Click() 

Dim num As Long 

' convert the number received from the InputBox to a number (type Long) 
num = CLng(Application.InputBox("enter num")) 

If CLng(TextBox1.Value) * num > CLng(TextBox2.Value) Then 
    MsgBox "textbox1 is higher" 
Else 
    MsgBox "textbox2 is higher" 
End If 

End Sub 
+0

を参照してくださいありがとう、これは私が理解することができる最も簡単な方法です.. –

1

あなたはそれを

を処理する前に好き入力検証が必要

Option Explicit 

Private Sub CommandButton1_Click() 
    Dim num As Long, tb1Val As Long, tb2Val As Long 
    Const DEFNUM As Long = 1 '<--| define a default value for 'num' 

    If Not ValidateInput(tb1Val, tb2Val) Then Exit Sub '<--| exit if textboxes have improper input 

    num = Application.InputBox("enter num", , DEFNUM, Type:=1) '<-_| 'Type:=1' forces a number input 
    With Me 
     If tb1Val * num > tb2Val.Value Then 
      MsgBox "textbox1 is higher" 
     Else 
      MsgBox "textbox2 is higher" 
     End If 
    End With 
End Sub 

Function ValidateInput(tb1Val As Long, tb2Val As Long) As Boolean 
    With Me 
     If IsNumber(.TextBox1) And IsNumber(.TextBox2) Then 
      tb1Val = CLng(.TextBox1.Value) 
      tb2Val = CLng(.TextBox2.Value) 
      ValidateInput = True 
     Else 
      MsgBox "Improper textbox input, try again", vbCritical 
     End If 
    End With 
End Function 
を次の

あなたが見ることができるように:

  • Function ValidateInput()に求め

    がしたいことがあり、関連するuserfom入力の検証は、あなたの実際のニーズに合わせてそれを変更する

  • Application.InputBox()機能の代わりVBA.InputBox()を使用しましたそのTypeパラメータを利用して、入力を強制的に数字にします。

は、私はあなたが、これは、...ちょうどType conversion functionCDbl()CInt()対応して必要なデータ型(DoubleInteger、...)とCLng()を持つすべてのLong出現箇所を変更する場合であってはならない、Long番号を必要とすると仮定

+0

++うまく説明:) –

+0

ありがとう@SiddharthRout – user3598756

+0

ありがとうございました。それは私のために働いた。 –

0

あなたがしなければならなかったことは、TextBox値を取得するときにVal()関数を使うことでした。あなたのコードに応じてTextBox1.Value

Private Sub CommandButton1_Click() 

Dim num As String 
num = Application.InputBox("enter num") 
If Val(TextBox1.Value) * num > Val(TextBox2.Value) Then 
    MsgBox "textbox1 is higher" 
Else 
    MsgBox "textbox2 is higher" 

End If 

End Sub 
関連する問題