[[SoftwareEngineering]] *ファイルに書き込む [#z1a61847] **Print文 [#o875650d] Dim freeFileNo As Integer ' ファイルの空き番号を取得 freeFileNo = FreeFile Open "D:\UDF\VBA\ファイル書き込みテスト.txt" For Output As #freeFileNo Print #freeFileNo, "あいうえお" Print #freeFileNo, "かきくけこ" Print #freeFileNo, "さしすせそ" Close #freeFileNo *引数の数を可変にする方法 [#v05d48b6] Public Sub Test_sprintf() Debug.Print sprintf("_{0}_{1}_{2}_{0}_{1}_{2}", "A", "b", "C") End Sub Private Function sprintf(template As String, ParamArray args() As Variant) As String Dim index As Integer value = template index = 0 For Each arg In args value = Replace(value, "{" & index & "}", arg) index = index + 1 Next sprintf = value End Function *Scripting.FileSystemObject [#td3b908c] -テキスト.txt あいうえお かきくけこ さしすせそ -Excel VBA Option Explicit Private Enum InOutMode ReadOnly = 1 Create = 2 Append = 8 End Enum Public Sub ReadTextFile() Dim filePath As String: filePath = ThisWorkbook.Path & "\テキスト.txt" Dim fileSystem As Object: Set fileSystem = CreateObject("Scripting.FileSystemObject") Dim readingFile As Object: Set readingFile = fileSystem.OpenTextFile(filePath, InOutMode.ReadOnly, False) Do Until (readingFile.AtEndOfStream) Debug.Print readingFile.ReadLine Loop readingFile.Close Set readingFile = Nothing Set fileSystem = Nothing End Sub *文字列を埋め込む [#yaeb80cc] Public Function FormatString(format As String, ParamArray args() As Variant) As String Dim index As Integer ''' <summary>指定した文字列の書式項目を、指定した配列内の対応するオブジェクトの文字列形式に置換します。</summary> Public Function StringFormat(Format As String, ParamArray Arguments() As Variant) As String StringFormat = Format FormatString = format Dim Index As Integer: Index = 0 Dim Argument As Variant For Each Argument In Arguments StringFormat = Replace(StringFormat, "{" & Index & "}", Argument) Index = Index + 1 Next For index = 0 To UBound(args()) FormatString = Replace(FormatString, "{" & index & "}", args(index)) Next index End Function Public Sub TestFormatString() Debug.Print FormatString("引数1=[{0}], 引数2=[{1}], 引数3=[{2}]", "param1", "param2", "param3") End Sub Public Function TestStringFormat() Debug.Assert ("2015/12/31" = StringFormat("{0}/{1}/{2}", "2015", "12", "31")) Debug.Assert ("2015/12/31" = StringFormat("2015{0}12{0}31", "/")) ' Arguments が多いケース Debug.Assert ("2015/12/31" = StringFormat("2015{0}12{0}31", "/", ".")) ' Arguments が少ないケース Debug.Assert ("2015/12/{2}" = StringFormat("{0}/{1}/{2}", "2015", "12")) ' 置換する文字列の連番が 0 から始まらないケース Debug.Assert ("12/31/{3}" = StringFormat("{1}/{2}/{3}", "2015", "12", "31")) End Function //End 文字列を埋め込む