実際に動くものを作ってみましたので参考として紹介します。
まず、時刻表をこんな感じで用意します。
山の手線の始発を参考にしました。
私の場合はユーザーフォームで入力して結果をメッセージボックスに表示する方法にしました。
ComboBox1,ComboBox2,TextBox1,CommandButton1,CommandButton2,CommandButton3を配置しました。
コードはこんな感じです。
Option Explicit '出発時刻ボタン Private Sub CommandButton1_Click() Call syori1(ComboBox1.ListIndex) End Sub '到着時刻ボタン Private Sub CommandButton2_Click() Call syori1(ComboBox2.ListIndex) End Sub 'メイン処理 Sub syori1(eki As Integer) If Not IsDate(TextBox1.Value) Or _ ComboBox1.Value = "" Or ComboBox2.Value = "" Or _ ComboBox1.ListIndex = -1 Or ComboBox1.ListIndex = -1 Then MsgBox "正しい値を入力してください" Exit Sub End If Dim syuppatu As Integer Dim toutyaku As Integer Dim str As String Dim myTime As Date Dim lastColumn As Integer Dim i As Integer Dim j As Integer syuppatu = ComboBox1.ListIndex toutyaku = ComboBox2.ListIndex 'ここで下りと上りの判別 If syuppatu >= toutyaku Then MsgBox "正しい値を入力してください" Exit Sub End If myTime = TimeSerial(Hour(TimeValue(TextBox1.Value)), Minute(TimeValue(TextBox1.Value)), 0) With Worksheets("時刻表") lastColumn = .Cells(1, Columns.Count).End(xlToLeft).Column For i = 2 To lastColumn If .Cells(eki + 2, i).Value > myTime Then Exit For End If Next i = i - 1 For j = 0 To 2 If i - j <= 1 Then Exit For str = str & .Cells(1, i - j) & vbNewLine Next j End With If str = "" Then str = "存在しません" MsgBox str End Sub 'キャンセル Private Sub CommandButton3_Click() Unload Me End Sub 'ユーザーフォームを表示するときにコンボボックスに駅名を設定 Private Sub UserForm_Initialize() Dim lastRow As Long Dim i As Long With Worksheets("時刻表") lastRow = .Cells(Rows.Count, 1).End(xlUp).Row For i = 2 To lastRow ComboBox1.AddItem (.Cells(i, 1).Value) ComboBox2.AddItem (.Cells(i, 1).Value) Next i End With End Sub
これだけなら、実はワークシート関数だけでvlookupとか使えばできそうでもあります。
例えば上り下りの時刻表を用意したり、時刻表には途中で終点の列車もあるのでそれに対応するなど
後々機能を拡張することを考えればVBAでもいいですけどね。
オブジェクトが見つからないというエラーなので、
ユーザーフォームに配置したコントロールの名前が違うようです。
あくまでも参考なので、コントロール名などは自分の環境に合わせる必要があります。
図の左上から
ComboBox1,ComboBox2,TextBox1,
CommandButton1,CommandButton2,CommandButton3
という名前なのでコントロールの方をそれに合わせてください。
変更の仕方は、ユーザーフォームを作る画面でコントロールを選択して
右クリックから出るプロパティの【オブジェクト名】というところで変更してください。
なんとかできたのですが、何度実行を試してみても「存在しません」
というメッセージしかでてこないのですが、これはどうしたらちゃんとなりますか?
回答者 | 回答 | 受取 | ベストアンサー | 回答時間 | |
---|---|---|---|---|---|
1 | SALINGER | 3454回 | 2392回 | 969回 | 2009-01-27 20:33:07 |
メイン処理の
If Not IsDate(TextBox1.Value) Or _
ComboBox1.Value = "" Or ComboBox2.Value = "" Or _
ComboBox1.ListIndex = -1 Or ComboBox1.ListIndex = -1 Then
のところで、エラー424が発生します。デバッグすると黄色で囲まれいます。
どうやったら直りますか?