SoftwareEngineering

ファイルに書き込む

Print文

Dim freeFileNo As Integer

' ファイルの空き番号を取得
freeFileNo = FreeFile


Open "D:\UDF\VBA\ファイル書き込みテスト.txt" For Output As #freeFileNo

Print #freeFileNo, "あいうえお"
Print #freeFileNo, "かきくけこ"
Print #freeFileNo, "さしすせそ"

Close #freeFileNo

引数の数を可変にする方法

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

  • テキスト.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
     
    

文字列を埋め込む

''' <summary>指定した文字列の書式項目を、指定した配列内の対応するオブジェクトの文字列形式に置換します。</summary>
Public Function StringFormat(Format As String, ParamArray Arguments() As Variant) As String
    StringFormat = 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
    
End Function



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

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2015-07-17 (金) 00:37:46 (1589d)