LoginSignup
0
1

More than 5 years have passed since last update.

VBA_クリップボードに文字列を代入(clip.exe使用)

Last updated at Posted at 2019-01-26

1.概要

クリップボードにテキストを反映する手法において、clip.exeを使用したもの。
・WinAPIを使用せずに出来ないか考え作成した。(結局ソースは煩雑になったためあまり意味は無かったかも)
・tempファイルは実行後にKillしたかったが何故かメモリリークし上手くいかなかったので諦めた。

(備考)DataObjectは簡単にクリップボードにアクセスできるが、クリップボードに文字列を代入する場合、全角が含まれると失敗する。

2.ソースコード

Option Explicit

Public Sub testRunClipEXE()

    Dim buf As String
    buf = "testテスト"

    Dim mypath As String

    Call RunClipEXE(buf)

    'この後ペーストすると"testテスト"が貼り付けられる

End Sub


'clip.exeを使用しクリップボードにarg_strを反映する。
'※clip.exe:Win標準のコマンドラインからクリップボードに値を挿入するプログラム
Public Function RunClipEXE(ByVal arg_str As String)

'手順:① 一時ファイル.txtを作成
'      ② 一時ファイルに引数を書き込み
'      ③ clip.exeで一時ファイルの内容をクリップボードに反映

'①
    '一時ファイルのパス
    Dim tmpPath As String
    tmpPath = ThisWorkbook.Path & "\RunClipEXE_temp.txt"

    'ファイル番号を取得し、一時ファイルを開く。
    Dim FileNumber As Integer
    FileNumber = FreeFile
    Open tmpPath For Output As #FileNumber

'②
    '一時ファイルに引数を書き込み
    Print #FileNumber, arg_str

    'ファイルを閉じる。
    Close #FileNumber

'③
    'WSHオブジェクトを作成
    Dim WSHobj As Object
    Set WSHobj = CreateObject("WScript.Shell")

    'clip.exeを実行し、でtmpPathのテキストをクリップボードにコピー
    '引数0はコマンドラインの非表示設定
    Call WSHobj.Run("cmd /c clip.exe < """ & tmpPath & """", 0)

End Function


3.出力結果

~略~

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1