top of page

Excel VBA テキストボックスの文字列選択、Backspace、Forward Delete

BackspaceキーやDeleteキーの代わりにコマンドボタンを使ってテキストボックスの文字の削除を行うマクロです。

機能

‐ 文字が選択されている場合は、その文字を削除します。

‐ Backspace: カーソルの位置の左側の文字を一文字削除します。

- Delete: カーソルの位置の右側の文字を一文字削除します。

- 文字列を全て選択します。

使い方

‐ 下記のサンプルコードを標準モジュールに貼り付ける。

‐ ユーザーフォームにテキストボックス、ボタンを配置する。

- ボタンのClickイベントプロシージャーに Call txtBackSpace(Me.TextBox1) などと書いて必要なプロシージャーを標準モジュールから呼び出す。

 

サンプルコード

'標準モジュールに貼り付ける

'テキストボックス内のカーソル位置の左側一文字を削除する

Sub txtBackSpace(txt As msforms.TextBox) Dim curString As String, selStart As Long, selLen As Long With txt curString = .Value '現在txtに入っている文字列 selStart = .selStart 'カーソルの位置 selLen = .SelLength '選択されている文字の数 'カーソルが左端にあり、かつ、文字が選択されていない場合は何もしない If selStart = 0 And selLen = 0 Then Exit Sub Select Case selLen Case Is = 0 '文字が選択されていない場合、カーソルの左側にある文字を一文字削除する     '左端からカーソル位置の一文字左までの文字列 & カーソル位置の一文字右から右末端までの文字列を結合 .Value = Left(curString, selStart - 1) & Mid(curString, selStart + 1, Len(curString)) selStart = selStart - 1 Case Is > 0 '文字が一文字以上選択されている場合、選択されている文字をすべて削除する     '左端からカーソル位置までの文字列 & 選択範囲右端から右末端までの文字列 .Value = Left(curString, selStart) & Mid(curString, selStart + selLen + 1, Len(curString)) End Select If selStart < 1 Then'カーソルが左端にある場合 .selStart = 0 Else .selStart = selStart End If End With

End Sub 'テキストボックス内のカーソル位置の右側一文字を削除する Sub txtFwdSpace(txt As msforms.TextBox) Dim curString As String, selStart As Long, selLen As Long With txt curString = .Value '現在txtに入っている文字列 selStart = .selStart 'カーソルの位置 selLen = .SelLength '選択されている文字の数

'カーソルが右末端にあり、かつ、文字が選択されていない場合は何もしない If selStart = Len(curString) And selLen = 0 Then Exit Sub

Select Case selLen Case Is = 0 '文字が選択されていない場合、カーソルの右側にある文字を一文字削除する .Value = Left(curString, selStart) & Mid(curString, selStart + 2, Len(curString)) Case Is > 0 '文字が一文字以上選択されている場合、選択されている文字をすべて削除する .Value = Left(curString, selStart) & Mid(curString, selStart + selLen + 1, Len(curString)) End Select If selStart >= Len(.Value) Then'カーソルが右端にある場合 .selStart = Len(.Value) Else .selStart = selStart End If End With

End Sub 'テキストボックス内の文字列を全て選択する Sub txtSelectAll(txt As msforms.TextBox) With txt .SetFocus .selStart = 0 .SelLength = Len(txt.Value) End With End Sub

特集記事
最新記事
アーカイブ
タグから検索
ソーシャルメディア
  • Facebook Basic Square
  • Twitter Basic Square
  • Google+ Basic Square
bottom of page