Friday, January 29, 2021

office (vba) - How to load data from text file into excel

If you have this text file with two columns, first with key, second with value:
osc;value
476;56
113;102
272;32.5
This VBA macro code enables to load data, check key comparing with first A column, if key is equal (exactly, if starts with key), then fill value into column R.
Sub Import()
  
  Dim file As String
  Dim counter As Integer
  Dim arr() As String
  Dim key As String
  Dim rngFound As Range
  Dim sheet As Worksheet
  Dim cell As Object
  
  file = Application.GetOpenFilename("Data files (*.txt),*.txt", Title:="Select file")
  
  If file = "False" Then Exit Sub
  
  ' Open file for reading
  
  Set sheet = ActiveSheet
  counter = 1
  
  Open file For Input As #1
  Do Until EOF(1)
    Line Input #1, textline
    
    ' Header - omit it
    If counter <> 1 Then
    
        arr = Split(textline, ";")
                
        ' Find row key value
        For Each cell In sheet.UsedRange.Rows
          
          key = sheet.Cells(cell.Row, "A").Value
                    
          If key <> "" Then
            If key Like arr(0) + "*" Then                
                
                sheet.Cells(cell.Row, "R") = arr(1)
                
            End If
          End If
                    
        Next cell
       
        ' MsgBox (arr(0) + "=" + arr(1))
    End If
        
    counter = counter + 1
  Loop
  Close #1
  
  MsgBox ("Hotovo")
  
End Sub
Output:

No comments:

Post a Comment