Search code examples
vbastringtextvariable-length-array

VBA - Reading a text file, splitting it into array and printing it back in VBA Word


Hello I would like to take my txt file containing string of data, split it into array by line. However, I am not able to either input data to array correctly or I have problem with the function GetArrLength. I am pretty new to VBA and can't figure the problem out. The macro stops with Run-time error '13': type mismatch and highlights this section of the code:

GetArrLength = UBound(arr) - LBound(arr) + 1

Hopefully it's not a big issue. Thanks for any ideas.

Sub apokus()

'PURPOSE: Send All Data From Text File To A String Variable


Dim TextFile As Integer
Dim filePath As String
Dim FileContent As String
Dim strAll As String
Dim arrString() As String

'File Path of Text File
  filePath = InputBox("Path to your MD file.", "Path to MD", "actual path to the file")


'Determine the next file number available for use by the FileOpen function
  TextFile = FreeFile
  
'Open the text file
  Open filePath For Input As TextFile
  
'Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)
  Close TextFile
  
arrString = Strings.Split(FileContent, vbCr)
Selection.TypeText Text:=GetArrLength(1)
Dim i As Long
For i = 1 To GetArrLength(arrString)
   Selection.TypeText Text:=GetArrLength(i) + vbNewLine
Next i

End Sub
Public Function GetArrLength(arr As Variant) As Long
   If IsEmpty(arr) Then
      GetArrLength = 0
   Else
      GetArrLength = UBound(arr) - LBound(arr) + 1
   End If
End Function

Solution

  • Your code should be as follows:

    arrString = Strings.Split(FileContent, vbCr)
    Selection.TypeText Text:=GetArrLength(arrString)
    Dim i As Long
    For i = 0 To UBound(arrString)
       Selection.TypeText Text:=arrString(i) + vbNewLine
    Next i
    

    However, I can't see the point of your code. You take a text file that contains a number of paragraphs, remove the carriage returns, then insert the text into Word adding carriage returns back in.