2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VBAで文字列、数値をSQLのIN句に入れる形にする

Last updated at Posted at 2019-11-13

2019/12/19追記:下記コードの改善版でも記事を書いてみましたのでよろしければご確認ください。シートを汚さずにクリップボードに直接放り込む

初投稿です。

前書き

私は業務でSQLを触るが、文字列を「'」で囲み「,」で区切るのが面倒でした。サクラエディタでAlt+ドラッグで複数行選択して付けていたがそれも面倒になってきたので作成しました。

Selection.Valueの値を文字列連結で変形

StringStyle.bas
Sub StringFormat()

    Dim longNum As Long
    Dim strValue As String
    
    strValue = Selection(1).Value
    strValue = "''" & strValue & "'"
    Selection(1).Value = strValue
    
    For longNum = 2 To Selection.Count Step 1
        strValue = Selection(longNum).Value
        strValue = ",'" & strValue & "'"
        Selection(longNum).Value = strValue
    Next
    
End Sub

後処理

証跡としてデータを綺麗にしたいときは下記。


```vb:StringCleansing
Sub StringCleansing()

    Dim longNum1 As Long
    Dim intLength As Integer
    Dim strValue As String
    
    For longNum = 1 To Selection.Count Step 1
        strValue = Selection(longNum).Value
        intLength = Len(Selection(longNum).Value) - 2
        strValue = Mid(strValue, 2, intLength)
        Selection(longNum).Value = strValue
    Next
    
End Sub

あとがき

クリップボードに入れる際に付加すればこんな二度手間いらないかなと書き終わった今思いました。
そもそもVBAでDBに直接接続してデータを抽出するのが一番楽なのだと思いますが、DB(Oracle)に接続する段階で詰まっており、とりあえず今はこれで対応しています。
精進いたします。

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?