忍者ブログ

◆当blogは、Linuxサーバ構築する際の実際の設定手順を個人的メモとして記載しております。LinuC試験の役に立つ情報があるかも…?

LinuC(Linux技術者認定資格)&リナックスサーバ構築設定事例

   
カテゴリー「VBA」の記事一覧

【VBA】列結合

Sub CombineCSVColumnsFromList()
  '#********************** 
  '#【変数定義】
  '#********************** 
  Dim fso As Object
  Dim scriptPath As String, listPath As String
  Dim ts As Object, line As String
  Dim csvFiles() As String, fileCount As Long
  Dim i As Long, r As Long
  Dim currentBook As Workbook, targetSheet As Worksheet
  Dim csvBook As Workbook, csvSheet As Worksheet
  Dim lastRow As Long, maxRow As Long
  Dim firstFileName As String, nextFileName As String
  Dim currentDate As String, excelFileName As String
  
  '#********************** 
  '#① マクロを実行しているExcelファイルと
  '#同じフォルダーのパスを取得
  '#********************** 
  Set fso = CreateObject("Scripting.FileSystemObject")
  scriptPath = ThisWorkbook.Path
  listPath = fso.BuildPath(scriptPath, "list.txt") '● リストファイルのパス取得
  
  '#********************** 
  '#【リストファイルの存在チェック】
  '#********************** 
  If Not fso.FileExists(listPath) Then
      MsgBox "エラー: リストファイル無し", vbCritical
      Exit Sub
  End If
  
  '#********************** 
  '#② リストファイルから対象CSVのフルパス読込
  '#********************** 
  fileCount = 0
  Set ts = fso.OpenTextFile(listPath, 1) '● 1 = ForReading
  Do Until ts.AtEndOfStream
      line = Trim(ts.ReadLine)
      If line <> "" Then
          Dim fullPath As String
          fullPath = fso.BuildPath(scriptPath, line)
          If fso.FileExists(fullPath) Then
              ReDim Preserve csvFiles(fileCount)
              csvFiles(fileCount) = fullPath
              fileCount = fileCount + 1
          End If
      End If
  Loop
  ts.Close
  
  '#********************** 
  '#【ファイル数のチェック】
  '#********************** 
  If fileCount < 2 Then
      MsgBox "エラー: 対象CSVファイルが2個未満", vbCritical
      Exit Sub
  End If
  
  '#********************** 
  '#【エラーハンドリング開始】
  '#********************** 
  On Error GoTo ErrorHandler
  
  '#********************** 
  '#【処理速度の高速化】
  '#【画面更新、警告、自動計算をオフ】
  '#********************** 
  Application.ScreenUpdating = False
  Application.DisplayAlerts = False
  Application.Calculation = xlCalculationManual
  
  '#********************** 
  '#③ 新しいワークブックを作成
  '#書き込み対象のシートを設定
  '#********************** 
  Set currentBook = Workbooks.Add(xlWBATWorksheet)
  Set targetSheet = currentBook.Sheets(1)
  
  '#********************** 
  '#④ 1番目のCSVファイルを処理
  '#(1列目[A列] と *列目[*列] を抽出)
  '#********************** 
  firstFileName = fso.GetBaseName(csvFiles(0))
  Set csvBook = Workbooks.Open(csvFiles(0))
  Set csvSheet = csvBook.Sheets(1)
  
  lastRow = csvSheet.Cells(csvSheet.Rows.Count, "A").End(xlUp).Row
  maxRow = lastRow '● 基準となる行数を保持
  
  '#********************** 
  '#【ヘッダーの書き込み】
  '#********************** 
  targetSheet.Cells(1, 1).Value = "Col1"
  targetSheet.Cells(1, 2).Value = firstFileName
  
  '#********************** 
  '#【データのコピー】
  '#1個目のCSVファイルの1列、N列
  '#********************** 
  For r = 1 To maxRow
     targetSheet.Cells(r + 1, 1).Value = csvSheet.Cells(r, 1).Value '● 1列/A列 (H0)
  '#targetSheet.Cells(r + 1, 2).Value = csvSheet.Cells(r, 2).Value '● 2列/B列 (H1)
     targetSheet.Cells(r + 1, 2).Value = csvSheet.Cells(r, 3).Value '● 3列/C列 (H2)
  '#targetSheet.Cells(r + 1, 2).Value = csvSheet.Cells(r, 4).Value '● 4列/D列 (H3)
  '#targetSheet.Cells(r + 1, 2).Value = csvSheet.Cells(r, 5).Value '● 5列/E列 (H4)
  Next r
  csvBook.Close SaveChanges:=False
  
  '#********************** 
  '#⑤ 2個目以降のCSVファイルを処理
  '#(*列目[*列] のみを横に結合)
  '#********************** 
  For i = 1 To fileCount - 1
      nextFileName = fso.GetBaseName(csvFiles(i))
      Set csvBook = Workbooks.Open(csvFiles(i))
      Set csvSheet = csvBook.Sheets(1)
      
  '#********************** 
  '#【ヘッダーの書き込み】
  '#(C列、D列…と右へ追加)
  '#********************** 
      targetSheet.Cells(1, i + 2).Value = nextFileName
      
  '#********************** 
  '#【データのコピー】
  '#2個目のCSVファイルのN列
  '#********************** 
      For r = 1 To maxRow
      '#targetSheet.Cells(r + 1, i + 2).Value = csvSheet.Cells(r, 2).Value '● 2列/B列 (H1)
         targetSheet.Cells(r + 1, i + 2).Value = csvSheet.Cells(r, 3).Value '● 3列/C列 (H2)
      '#targetSheet.Cells(r + 1, i + 2).Value = csvSheet.Cells(r, 4).Value '● 4列/D列 (H3)
      '#targetSheet.Cells(r + 1, i + 2).Value = csvSheet.Cells(r, 5).Value '● 5列/E列 (H4)
      Next r
      csvBook.Close SaveChanges:=False
  Next i
  
  '#********************** 
  '#⑥ 列幅の自動調整 (AutoFit)
  '#********************** 
  targetSheet.UsedRange.Columns.AutoFit
  
  '#********************** 
  '#⑦ ファイル名を指定して保存
  '#Excel 97-2003形式(.xls)
  '#********************** 
  currentDate = Format(Date, "yyyyMMdd")
  excelFileName = "_" & firstFileName & "_" & currentDate & "_★" & ".xls"
  
  '#********************** 
  '#【xlExcel8 = 56】
  '#(Excel 97-2003 ブック形式)
  '#********************** 
  currentBook.SaveAs Filename:=fso.BuildPath(scriptPath, excelFileName), FileFormat:=56
  currentBook.Close SaveChanges:=False
  
  MsgBox "【処理完了】" & vbCrLf & excelFileName, vbInformation
  
'#********************** 
'#【終了処理】
'#(ExitProcedure)
'#********************** 
ExitProcedure:
  '#********************** 
  '#画面更新、警告、自動計算を元に戻す
  '#********************** 
  Application.ScreenUpdating = True
  Application.DisplayAlerts = True
  Application.Calculation = xlCalculationAutomatic
  Exit Sub
  
'#********************** 
'#【エラーハンドリング処理を実行】
'#(ErrorHandler)
'#********************** 
ErrorHandler:
  MsgBox "【予期せぬエラー発生の為、処理中断】" & vbCrLf & _
         "エラー番号: " & Err.Number & vbCrLf & _
         "エラー内容: " & Err.Description, vbCritical
  
  '#********************** 
  '#【開きっぱなしのCSVや作成中ファイルを閉じる】
  '#(必要に応じて実行)
  '#********************** 
  On Error Resume Next
  If Not csvBook Is Empty Then csvBook.Close SaveChanges:=False
  If Not currentBook Is Empty Then currentBook.Close SaveChanges:=False
  
  '#********************** 
  '#【終了処理(ExitProcedure)へ移動】
  '#********************** 
  Resume ExitProcedure
  
End Sub
PR

【VBA】日付表示を「月/日.」に変更する処理

Option Explicit
'▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼
 Sub main()
   '--- --- --- --- --- --- --- --- --- ---
   '□ 最終行の取得
   '--- --- --- --- --- --- --- --- --- ---
    Dim Last_Row As Long                                  '最終行数用変数
    Last_Row = 0                                                 '最終行数の変数をゼロクリア
    Last_Row = Cells(1, "B").End(xlDown).Row  '最終行の数を取得
   '--- --- --- --- --- --- --- --- --- ---
   '--- --- --- --- --- --- --- --- --- ---
   '□ 日付の表示変更(シリアル値 ⇒ m/d形式)
   '--- --- --- --- --- --- --- --- --- ---
   Dim Row_i As Long         'ループカウント用
   Dim A_Value As Variant  'セルの値を格納

   For Row_i = 2 To Last_Row

      A_Value = Cells(Row_i, "B").Value
      MsgBox A_Value

      '# 文字の長さ判定

      If Len(A_Value) < 7 Then
         '# 処理なし
      Else
         A_Value = Format(A_Value, "m/d")
         A_Value = A_Value & "."
      End If

      '# 文字の長さ判定

      If Len(A_Value) >= 8 Then
         A_Value = Mid(A_Value, 6)
      End If

      MsgBox A_Value

      Cells(Row_i, "B") = A_Value
   Next
   '--- --- --- --- --- --- --- --- --- ---
 End Sub
'▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼

【VBA】セル範囲を配列化する処理の関数

Option Explicit
'▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲
'■【メイン処理】
'▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼
 Sub main()
   
    Dim myRange As Range
    Dim F_Array() As String
    Erase F_Array()         '■ 配列初期化■
   
    Set myRange = ActiveSheet.Range("B2", "C20")        '■ セル範囲を格納■
   
    '***************************************
    '■【セル範囲を配列化する処理】
    '***************************************
    Call Func_03(myRange, F_Array())        '■ 関数呼び出し■
    Cells(22, "B") = F_Array(0)        '戻り値をセルに反映
    Cells(23, "B") = F_Array(1)        '戻り値をセルに反映
    Cells(24, "B") = F_Array(2)        '戻り値をセルに反映
    '***************************************
   
    Set myRange = Nothing
'★        myRange.Cells.SpecialCells(xlCellTypeBlanks).Interior.Color = RGB(255, 128, 128)
 
 End Sub
'▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼
'************************************************
'■【セル範囲を配列化する処理】
'************************************************
 Function Func_03(R_Range As Range, R_Array() As String)
   
    Dim myArray As Variant
    myArray = R_Range
    Dim Row_max, Column_max As Long '■ 行/列の変数■
    Row_max = UBound(myArray, 1)    '■ 行要素番号の最大値を取得(第二引数は省略可)■
    Column_max = UBound(myArray, 2) '■ 列要素番号の最大値を取得■
   
    Dim Row_i, Column_i As Long     '■ 行/列のカウント用変数■
    Dim Array_1, Array_2 As String  '■ 1列/2列の文字列を格納する変数■
    Dim Array_S As String           '■ 1列+2列を繋げて格納する変数■
    ReDim R_Array(Row_max - 1)
   
    '---------------------------------------
    '■ 配列の中身を確認
    '---------------------------------------
    For Row_i = 1 To Row_max
        Array_1 = myArray(Row_i, 1)
        Array_2 = myArray(Row_i, 2)
        Array_S = Array_1 & Array_2
        Cells(Row_i, "N") = Array_S       '■ セルに転記する■
        R_Array(Row_i - 1) = Array_S    '■ 戻り値として配列に格納■
    Next
    '---------------------------------------
   
    Set myArray = Nothing
 
 End Function
'************************************************

【VBA】最終行の取得方法(関数有り/関数無し)

Option Explicit
'▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼
 Sub main()
    Dim Fa As Long      '関数の引数1/戻り値1
    Dim Fb As Long      '関数の引数2/戻り値2
    Dim Fc As Long      '関数の引数3/戻り値3
    Fa = 0       'ゼロクリア
    Fb = 0       'ゼロクリア
    Fc = 0       'ゼロクリア
   
    '*** *** *** *** *** *** *** *** *** ***
    '■ 最終行の取得方法【関数有り】
    '*** *** *** *** *** *** *** *** *** ***
      Call Func_02(Fa, Fb, Fc)   '関数呼び出し
      Cells(1, "K") = Fa           '戻り値1を指定
      Cells(2, "K") = Fb           '戻り値2を指定
      Cells(3, "K") = Fc           '戻り値3を指定
    '*** *** *** *** *** *** *** *** *** ***

    '--- --- --- --- --- --- --- --- --- ---
    '□ 最終行の取得方法【関数無し】
    '--- --- --- --- --- --- --- --- --- ---
      Dim Etc_Row As Long     '不要な行数用変数
      Dim Last_Row As Long    '最終行数用変数
    
      Etc_Row = 1               '不要な行数の初期値
      Last_Row = 0              '最終行数の変数をゼロクリア
    
      Last_Row = Cells(1, "A").End(xlDown).Row       '最終行の数を取得
      Last_Row = Last_Row - Etc_Row                   '最終行数から不要な行数をマイナス
    
      Cells(1, "G") = Last_Row                            '結果を反映
      Cells(2, "G") = Etc_Row                             '結果を反映
      Cells(3, "G") = Cells(1, "A").End(xlDown).Row   '結果を反映
    '--- --- --- --- --- --- --- --- --- ---
 
 End Sub
'▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼

'************************************************
 Function Func_02(Ra As Long, Rb As Long, Rc As Long)
   
    Dim Result_01 As Long    '戻り値用変数1
    Dim Result_02 As Long    '戻り値用変数2
    Dim Result_03 As Long    '戻り値用変数3
    Result_01 = Ra       '引数1を格納
    Result_02 = Rb       '引数2を格納
    Result_03 = Rc       '引数3を格納
   
    '--- --- --- --- --- --- --- --- --- ---
    Dim i As Long                   'ループカウンター用変数
    i = 2                             'ループ開始行を設定
    '--- --- --- --- --- --- --- --- --- ---
   
    '--- --- --- --- --- --- --- --- --- ---
    Do While Cells(i, "A") <> ""      '空欄になるまでループ
        i = i + 1                        'ループカウントアップ
        Result_01 = Result_01 + 1    '行数を加算
    Loop
    '--- --- --- --- --- --- --- --- --- ---

    Result_02 = i - Result_01
    Result_03 = i
   
    '--- --- --- --- --- --- --- --- --- ---
    '□ 戻り値が複数ある場合の書き方
    '--- --- --- --- --- --- --- --- --- ---
    Ra = Result_01    '戻り値を格納1
    Rb = Result_02    '戻り値を格納2
    Rc = Result_03    '戻り値を格納3
    '--- --- --- --- --- --- --- --- --- ---
 
 End Function
'************************************************

【VBA】簡単なエクセルマクロでの関数の記述例

※以下のような記述で関数の呼び出しと戻り値の利用が可能となる

=== === === === ===【以下は関数の記述例】=== === === === ===
Option Explicit
'▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼
 Sub main()

    Dim Fa As Long
    Dim Fb As Long
    Dim Fc As Long

    Fa = 0

    Fb = 0
    Fc = 0

    '--- --- --- --- --- --- --- ---

    '□ 値をセット
    '--- --- --- --- --- --- --- ---
     Fa = 2
     Fb = 3
     Fc = 10
    '--- --- --- --- --- --- --- ---

    '*** *** *** *** *** *** *** *** *** ***
    '■ 関数の結果をセルに反映
    '*** *** *** *** *** *** *** *** *** ***
     Cells(1, "A") = Func_01(Fa, Fb, Fc)
    '*** *** *** *** *** *** *** *** *** ***

 End Sub
'▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼

'************************************************
 Function Func_01(Ra As Long, Rb As Long, Rc As Long)

    Dim Result_01 As Long

    MsgBox Ra

    MsgBox Rb
    MsgBox Rc

    '--- --- --- --- --- --- --- ---

    '□ 引数を使って計算
    '--- --- --- --- --- --- --- ---
     Result_01 = Ra + Rb + Rc
    '--- --- --- --- --- --- --- ---

    '*** *** *** *** *** *** ***
    '■ 結果を戻り値とする
    '*** *** *** *** *** *** ***
     Func_01 = Result_01
    '*** *** *** *** *** *** ***

 End Function
'************************************************

更新日付

09 2026/10 11
S M T W T F S
1 2
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

RECOMMEND

プロフィール

HN:
Account
HP:
性別:
非公開
職業:
--- NODATA ---
趣味:
--- NODATA ---
自己紹介:
◆当blogは、Linuxサーバ構築する際の実際の設定手順を個人的メモとして記載しております。LinuC試験の役に立つ情報があるかも…?

リンク

 | HOME | 
Copyright ©  -- LinuC(Linux技術者認定資格)&リナックスサーバ構築設定事例 --  All Rights Reserved
Design by CriCri / Photo by Melonenmann / powered by NINJA TOOLS / 忍者ブログ / [PR]