Adsense

2019年8月27日火曜日

【ACCESS/EXCEL/VBA】末尾全角文字化け回避用 拡張LeftBサンプル



LeftBでは末尾の全角文字列1バイトが切られてしまう場合、末尾の全角文字列が文字化けする。
全角文字列の文字化けを考慮する場合は別途チェックが必要になる。


■文字化け回避用のLeftB拡張モジュールサンプル(末尾切り上げ/切り捨て、全半角混在も対応)
  1. ' 引数説明
  2. ' prm:対象文字列
  3. ' length:取得バイト数
  4. ' convert:True時Nullを""に変換/False時Nullをそのまま返す
  5. ' truncate:True時末尾切り捨て /False時末尾切り上げ
  6. Private Function ExLeftB(ByVal prm As Variant, _
  7. ByVal length As Integer, _
  8. Optional ByVal convert As Boolean = True, _
  9. Optional ByVal truncate As Boolean = True) As Variant
  10. Dim cnvStr As String
  11. ' Accessの場合
  12. cnvStr = StrConv(Nz(prm, ""), vbFromUnicode)
  13. ' Excelの場合
  14. ' cnvStr = StrConv(IIf(IsNull(prm), "", prm), vbFromUnicode)
  15. If LenB(cnvStr) <= length Then
  16. ExLeftB = IIf(convert, Nz(prm), prm)
  17. Exit Function
  18. End If
  19. Dim leftNormal As Variant
  20. Dim leftTrunc As Variant
  21. Dim leftRoundUp As Variant
  22. leftNormal = StrConv(LeftB(cnvStr, length), vbUnicode)
  23. leftTrunc = StrConv(LeftB(cnvStr, length - 1), vbUnicode)
  24. leftRoundUp = StrConv(LeftB(cnvStr, length + 1), vbUnicode)
  25. If Len(leftNormal) <> Len(leftRoundUp) Then
  26. ExLeftB = leftNormal
  27. Exit Function
  28. Else
  29. ExLeftB = IIf(truncate, leftTrunc, leftRoundUp)
  30. Exit Function
  31. End If
  32. End Function
  33.  


■使用例
  1. Private Sub dammy()
  2. Debug.Print ("---------------------")
  3. Debug.Print ("Nullコンバートする")
  4. Debug.Print (ExLeftB(Null, 3))
  5. Debug.Print ("---------------------")
  6. Debug.Print ("Nullコンバートしない")
  7. Debug.Print (ExLeftB(Null, 3, False))
  8. Debug.Print ("---------------------")
  9. Debug.Print ("切り捨て出力")
  10. Debug.Print (ExLeftB("あああ", 5))
  11. Debug.Print ("---------------------")
  12. Debug.Print ("切り上げ出力")
  13. Debug.Print (ExLeftB("あああ", 5, truncate:=False))
  14. Debug.Print ("---------------------")
  15. End Sub

■実行結果

2019年8月3日土曜日

【SQL Server】NULLを変換する(ISNULL,COALESCEの違い)


NULL変換を行う場合にはISNULL、COALESCEの2種類の変換方法がある。

①ISNULLを使用する場合
■書き方等
 ISNULL(第一引数, 第二引数)
 ISNULLは第一引数がNULLの場合に第二引数の値を返す。  戻り値型は第一引数と同じ。
■使用例
テーブル名:[TEST_TBL1]
column1column2column3column4
1列をNULLNULL
2NULL成せ汝NULL
3NULLNULL従順の下僕
4NULLNULLNULL

実行するSQL
  1. SELECT ISNULL(column1,'Big Brother') AS C1
  2. , ISNULL(column2,'Big Brother') AS C2
  3. , ISNULL(column3,'Big Brother') AS C3
  4. , ISNULL(column4,'Big Brother') AS C4
  5. FROM TEST_TBL1

実行結果
C1C2C3C4
1列をBig BrotherBig Brother
2Big Brother成せ汝Big Brother
3Big BrotherBig Brother従順の下僕
4Big BrotherBig BrotherBig Brother


②COALESCEを使用する場合
■書き方等  COALESCE(第一引数, 第二引数, 第三引数, …)
 COALESCEは第一引数から順番に評価を行い、NULLでない最初の引数を返す。
 戻り値型は引数で使用されている型の中で型の優先度が高いものが使用される。
■使用例
テーブル名:[TEST_TBL1]
column1column2column3column4
1列をNULLNULL
2NULL成せ汝NULL
3NULLNULL従順の下僕
4NULLNULLNULL


・例.1:第二引数まで指定する場合(ISNULL
 実行するSQL
  1. SELECT COALESCE(column1, 'Big Brother') AS C1
  2. , COALESCE(column2, 'Big Brother') AS C2
  3. , COALESCE(column3, 'Big Brother') AS C3
  4. , COALESCE(column4, 'Big Brother') AS C4
  5. FROM TEST_TBL1

 実行結果
C1C2C3C4
1列をBig BrotherBig Brother
2Big Brother成せ汝Big Brother
3Big BrotherBig Brother従順の下僕
4Big BrotherBig BrotherBig Brother

・例.2:第三引数以降も指定した場合
 実行するSQL
  1. SELECT COALESCE(column2 , column3, column4, 'BigBrother') AS C1
  2. FROM TEST_TBL1

 実行結果
C1
列を
成せ汝
従順の下僕
Big Brother

■ISNULLとCOALESCEの違い
引数に指定できる個数以外は同等にみえるが、
それぞれ変換後の型の扱いに違いがあることに注意が必要。

ISNULLは「第一引数と同じ」
COALESEは「引数で使用されている型の中で型の優先度が高いものが使用される」

例えば以下のようなSQLを実行した場合はCOALESEではエラーが発生することがある。
・ISNULLを使用した場合
  1. SELECT ISNULL('AAA' , 2) AS C1
C1
AAA

・COALESCEを使用した場合
  1. SELECT COALESCE('AAA' , 2) AS C1
メッセージ 245、レベル 16、状態 1、行 1
varchar の値 'AAA' をデータ型 int に変換できませんでした。

COALESCEを使用した場合はvarchar型の’AAA’を
型の優先度が高いint型に変換しようとしエラーが発生する。



2019年7月29日月曜日

【ACCESS/EXCEL/VBA】ログ出力を行うモジュールサンプル



ACCESSのみで動作確認をしていますがEXCELでもそのまま使えると思います。
かゆいところに手が届かない部分や雑な箇所があるので、必要に応じてカスタマイズして使用してください。


①ファイル出力処理用に
 事前に[ツール]→[参照設定]から[Microsoft Scripting Runtime]を追加する


②以下ログ出力モジュール
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Private Type systemTime
  5. Year As Integer
  6. Month As Integer
  7. DayOfeek As Integer
  8. Day As Integer
  9. Hour As Integer
  10. Minute As Integer
  11. Second As Integer
  12. Milliseconds As Integer
  13. End Type
  14.  
  15. Private Declare Sub GetSystemTime Lib "kernel32" (systemTime As systemTime)
  16. Private MeasureStartTime As systemTime
  17. Private MeasureEndTime As systemTime
  18. Private IntermStartTime As systemTime
  19. Private IntermEndTime As systemTime
  20. Private MeasureLog As String
  21.  
  22. Public Sub MeasureStart()
  23. MeasureStartTime = GetDetailSysTime
  24. MeasureLog = "計測開始:" & GetFormatSysTime(MeasureStartTime) & vbCrLf
  25. End Sub
  26.  
  27. Public Sub MeasureEnd()
  28. MeasureEndTime = GetDetailSysTime
  29. MeasureLog = MeasureLog & _
  30. "計測終了:" & GetFormatSysTime(MeasureEndTime) & vbCrLf & _
  31. "計測時間:" & GetMeasureTime(IntermStartTime, IntermEndTime) & vbCrLf
  32. Call OutPutText("Log" & GetUnFormatSysTime(MeasureStartTime), MeasureLog)
  33. End Sub
  34.  
  35. Public Sub IntermStart()
  36. IntermStartTime = GetDetailSysTime
  37. End Sub
  38.  
  39. Public Sub IntermEnd(ByVal text As String)
  40. IntermEndTime = GetDetailSysTime
  41. MeasureLog = MeasureLog & _
  42. text & _
  43. ":" & _
  44. GetFormatSysTime(IntermStartTime) & vbTab & _
  45. GetFormatSysTime(IntermEndTime) & vbTab & _
  46. GetMeasureTime(IntermStartTime, IntermEndTime) & vbCrLf
  47. End Sub
  48.  
  49. Public Sub AddLog(ByVal text As String)
  50. MeasureLog = MeasureLog & _
  51. text & _
  52. ":" & vbTab & _
  53. GetFormatSysTime(GetDetailSysTime) & vbCrLf
  54. End Sub
  55.  
  56. Private Function GetDetailSysTime() As systemTime
  57. Dim sysTime As systemTime
  58. GetSystemTime sysTime
  59. GetDetailSysTime = sysTime
  60. End Function
  61.  
  62. Private Sub OutPutText(ByVal fileName As String, ByVal text As String)
  63. Dim wsh As Object
  64. Set wsh = CreateObject("WScript.Shell")
  65. Dim fso As FileSystemObject
  66. Set fso = New FileSystemObject
  67.  
  68. Dim ts As TextStream
  69. Set ts = fso.CreateTextFile(wsh.SpecialFolders("Desktop") & "\" & fileName & ".txt", Overwrite:=True, Unicode:=True)
  70.  
  71. ts.Write (text)
  72. ts.Close
  73. Set wsh = Nothing
  74. Set ts = Nothing
  75. Set fso = Nothing
  76. End Sub
  77.  
  78. Private Function GetFormatSysTime(ByRef sysTime As systemTime) As String
  79. GetFormatSysTime = CStr(sysTime.Year) & "/" & _
  80. Format(sysTime.Month, "00") & "/" & _
  81. Format(sysTime.Day, "00") & " " & _
  82. Format(sysTime.Hour, "00") & ":" & _
  83. Format(sysTime.Minute, "00") & ":" & _
  84. Format(sysTime.Second, "00") & "." & _
  85. Format(sysTime.Milliseconds, "000")
  86. End Function
  87.  
  88. Private Function GetUnFormatSysTime(ByRef sysTime As systemTime) As String
  89. GetUnFormatSysTime = CStr(sysTime.Year) & _
  90. Format(sysTime.Month, "00") & _
  91. Format(sysTime.Day, "00") & _
  92. Format(sysTime.Hour, "00") & _
  93. Format(sysTime.Minute, "00") & _
  94. Format(sysTime.Second, "00") & _
  95. Format(sysTime.Milliseconds, "000")
  96. End Function
  97.  
  98. Private Function GetMeasureTime(ByRef sysStartTime As systemTime, _
  99. ByRef sysEndTime As systemTime) As String
  100. Dim startTime As Double
  101. Dim endTime As Double
  102. startTime = CDbl(Format(sysStartTime.Hour, "00") & _
  103. Format(sysStartTime.Minute, "00") & _
  104. Format(sysStartTime.Second, "00") & "." & _
  105. Format(sysStartTime.Milliseconds, "000"))
  106. endTime = CDbl(Format(sysEndTime.Hour, "00") & _
  107. Format(sysEndTime.Minute, "00") & _
  108. Format(sysEndTime.Second, "00") & "." & _
  109. Format(sysEndTime.Milliseconds, "000"))
  110. GetMeasureTime = Format(CStr(endTime - startTime), "00:00:00.000")
  111. End Function



③使用例
1.MeasureStartでログを取得開始、
 MeasureEndでログファイルをデスクトップに出力します。
※MeasureStart/MeasureEnd処理は計測時には必須処理となります。
2.MeasureStart~End間の処理で以下の関数を実行すると中間ログの取得が行えます。  AddLog:引数テキスト、AddLog実行時の時刻をログファイルに出力します。  IntermStart/IntermEnd:IntermStartで中間ログ計測開始、
             IntermEndで引数テキスト、Start/End時刻、Start~End間の時間をログファイルに出力します。
  1. Private Sub LogSample()
  2. ' MeasureStart実行でログ計測を開始します
  3. Call MeasureStart
  4. ' 単純なログを残した場合はAddLogを使用します
  5. Call AddLog("AddLogサンプル①")
  6. ' 中間の処理時間を図りたい場合はIntermStart-IntermEndを使用します
  7. ' IntermEndの引数に指定した文言/IntermStartとEnd時刻/IntermEndまでの時間が出力されます。
  8. Call IntermStart
  9. ' --ダミー処理---
  10. Dim i As Long
  11. Dim str As String
  12. For i = 0 To 100000
  13. str = "dammy"
  14. Next i
  15. ' --ダミー処理---
  16. Call IntermEnd("IntermStart/End")
  17. Call AddLog("AddLogサンプル②")
  18. ' MeasureEnd実行でログファイルが出力されます
  19. Call MeasureEnd
  20. End Sub
④実行結果  [③使用例]のコードを実行した結果  以下のファイルがデスクトップに出力される。

2019年7月28日日曜日

【ACCESS/EXCEL/VBA】現在時刻ミリ秒まで取得を行う

VBAの[ NOW() ]や[ DATE() ]関数ではミリ秒の取得が行えない。
ミリ秒まで取得を行いたい場合は[ Win32API ]を使用して別途自作する必要がある。

■以下取得関数サンプル
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Private Type systemTime
  5. Year As Integer
  6. Month As Integer
  7. DayOfeek As Integer
  8. Day As Integer
  9. Hour As Integer
  10. Minute As Integer
  11. Second As Integer
  12. Milliseconds As Integer
  13. End Type
  14.  
  15. Private Declare Sub GetSystemTime Lib "kernel32" (systemTime As systemTime)
  16.  
  17. ' 現在日時をミリ秒まで取得する関数
  18. Public Function GetDetailSysTime() As String
  19. Dim sysTime As systemTime
  20. GetSystemTime sysTime
  21. GetDetailSysTime = CStr(sysTime.Year) & "/" & _
  22. Format(sysTime.Month, "00") & "/" & _
  23. Format(sysTime.Day, "00") & " " & _
  24. Format(sysTime.Hour, "00") & ":" & _
  25. Format(sysTime.Minute, "00") & ":" & _
  26. Format(sysTime.Second, "00") & "." & _
  27. Format(sysTime.Milliseconds, "000")
  28. End Function

【ACCESS/VBA】SQL文実行サンプル

  1. Private Sub ExecSQL()
  2. Dim cmd As New ADODB.Command
  3. Dim conn As New ADODB.Connection
  4. Dim rst As New ADODB.Recordset
  5. Dim rtn As Integer
  6. m_cn = New ADODB.Connection
  7. conn.ConnectionString = "DSN=TEST_ODBC;Uid=USER1;Pwd=userpass1;Database=TEST_DB"
  8. conn.Open
  9. Set cmd = New ADODB.Command
  10. Set cmd.ActiveConnection = conn
  11. ' SELECT文(レコードセットに結果取得するパターン)
  12. With cmd
  13. .CommandText = "SELECT * " & _
  14. "FROM TEST_TBL1 " & _
  15. "WHERE column1 = ? AND " & _
  16. " column2 = ?;"
  17. .CommandType = adCmdText
  18. .Parameters(0).Value = 1 ' 1つ目?へのバインド
  19. .Parameters(1).Value = "AAA" ' 2つ目?へのバインド
  20. End With
  21. Set rst = cmd.Execute
  22. rst.Close
  23. Set rst = Nothing
  24. ' UPDATE/INSERT文(レコードセットに結果取得しないパターン)
  25. With cmd
  26. .CommandText = "UPDATE TEST_TBL1 " & _
  27. "SET column2 = ? " & _
  28. "WHERE column1 = ?;"
  29. .CommandType = adCmdText
  30. .Parameters(0).Value = "BBB" ' 1つ目?へのバインド
  31. .Parameters(1).Value = 1 ' 2つ目?へのバインド
  32. End With
  33. Call cmd.Execute
  34.  
  35. With cmd
  36. .CommandText = "INSERT INTO TEST_TBL1(" & _
  37. " column1, " & _
  38. " column2 " & _
  39. ")VALUES(" & _
  40. " ?," & _
  41. " ?);"
  42. .CommandType = adCmdText
  43. .Parameters(0).Value = 2 ' 1つ目?へのバインド
  44. .Parameters(1).Value = "CCC" ' 2つ目?へのバインド
  45. End With
  46. Call cmd.Execute
  47. Set cmd = Nothing
  48. End Sub

【ACCESS/VBA】ストアドプロシージャ実行サンプル

①ストアド内のSELECT結果を取得する場合
  1. Private Sub ExecSP()
  2. Dim cmd As New ADODB.Command
  3. Dim conn As New ADODB.Connection
  4. Dim rst As New ADODB.Recordset
  5. Dim rtn As Integer
  6. m_cn = New ADODB.Connection
  7. conn.ConnectionString = "DSN=TEST_ODBC;Uid=USER1;Pwd=userpass1;Database=TEST_DB"
  8. conn.Open
  9. Set cmd = New ADODB.Command
  10. Set cmd.ActiveConnection = conn
  11. With cmd
  12. .CommandText = "usp_sp1"
  13. .CommandType = adCmdStoredProc
  14. .Parameters.Refresh
  15. .Parameters(1).Value = 100 ' ストアド引数1つ目
  16. .Parameters(2).Value = 200 ' ストアド引数2つ目
  17. End With
  18. ' ストアドプロシージャ内で最後に実行されたSQLの結果を取得
  19. Set rst = cmd.Execute
  20. ' ストアドプロシージャのReturn値を取得
  21. rtn = cmd.Parameters(0).Value
  22. rst.Close
  23. Set rst = Nothing
  24. Set cmd = Nothing
  25. End Sub
②ストアド内のSELECT結果を取得しない場合
  1. Private Sub ExecSP()
  2. Dim cmd As New ADODB.Command
  3. Dim conn As New ADODB.Connection
  4. Dim rst As New ADODB.Recordset
  5. Dim rtn As Integer
  6. m_cn = New ADODB.Connection
  7. conn.ConnectionString = "DSN=TEST_ODBC;Uid=USER1;Pwd=userpass1;Database=TEST_DB"
  8. conn.Open
  9. Set cmd = New ADODB.Command
  10. Set cmd.ActiveConnection = conn
  11. With cmd
  12. .CommandText = "usp_sp1"
  13. .CommandType = adCmdStoredProc
  14. .Parameters.Refresh
  15. .Parameters(1).Value = 100 ' ストアド引数1つ目
  16. .Parameters(2).Value = 200 ' ストアド引数2つ目
  17. .Execute
  18. End With
  19. ' ストアドプロシージャのReturn値を取得
  20. rtn = cmd.Parameters(0).Value
  21. rst.Close
  22. Set rst = Nothing
  23. Set cmd = Nothing
  24. End Sub

【ACCESS/VBA】ADODB接続サンプル

①事前に[ツール]→[参照設定]から[Microsoft ActiveX Data Objects X.X Library]を追加する
※参照設定を使用しない場合は不要
















②以下サンプル(接続文字列はODBC接続)
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Private Const CON_STRING As String = "DSN=TEST_ODBC;Uid=USER1;Pwd=userpass1;Database=TEST_DB"
  5. Private m_cn As New ADODB.Connection
  6.  
  7. ' コネクションオープン用
  8. Public Sub OpenConnection()
  9.     m_cn = New ADODB.Connection
  10.     m_cn.ConnectionString = CON_STRING
  11.     m_cn.Open
  12. End Sub
  13.  
  14. ' コネクションクローズ用
  15. Public Sub CloseConnection()
  16.     m_cn.Close
  17. End Sub
  18.  
  19. ' コネクション取得用
  20. Public Function GetConnection() As ADODB.Connection
  21.     Set GetConnection = m_cn
  22. End Function
③使用例
  1. Option Compare Database
  2. Private Sub test()
  3. Dim rst As New ADODB.Recordset
  4. Call OpenConnection
  5. rst.ActiveConnection = M_Connection.GetConnection
  6. rst.Open "select * from TEST_TBL1;"
  7. rst.Close
  8.  
  9. Set rst = Nothing
  10. Call CloseConnection
  11. End Sub