Gruppe
Extern
Bereich
TextImport
Thema
Werte aus Textdatei importieren und umwandeln
Problem
Aus einer Textdatei sollen Werte importiert und umgewandelt werden. Handelt es sich bei dem rechten Zeichen im Wert um ein H, ist der Wert positiv, bei einem S ist er negativ. Die Werte werden in die Tabelle eingetragen.
Lösung
Geben Sie den nachfolgenden Code in ein Standardmodul ein und weisen Sie ihn einer Schaltfläche zu.
StandardModule: Modul1
Sub Importieren()
Dim arr As Variant
Dim vValue As Variant
Dim iRow As Integer, iCol As Integer
Dim sFile As String, sTxt As String
sFile = ThisWorkbook.Path & "\setminus.txt"
If Dir(sFile) = "" Then
Beep
MsgBox "Kann die Textdatei " & sFile & " nicht finden!"
Exit Sub
End If
Close
Open sFile For Input As #1
Do Until EOF(1)
iRow = iRow + 1
Line Input #1, sTxt
arr = fncSplit(sTxt, vbTab)
For iCol = 0 To UBound(arr)
vValue = arr(iCol)
If Right(vValue, 1) = "H" Then
vValue = CDbl(Left(vValue, Len(vValue) - 1))
ElseIf Right(vValue, 1) = "S" Then
vValue = CDbl(Left(vValue, Len(vValue) - 1)) * -1
End If
Cells(iRow, iCol + 1).Value = vValue
Next iCol
Loop
Close
End Sub
Function fncSplit( _
SplitText As String, _
Delimiter As Variant _
) As Variant
Dim iFile As Integer, iCounter As Integer
Dim arr() As String
Dim sTxt As String
Do While SplitText <> ""
ReDim Preserve arr(iCounter)
If InStr(SplitText, Delimiter) Then
sTxt = Left(SplitText, _
InStr(SplitText, Delimiter) - 1)
arr(iCounter) = sTxt
SplitText = Right(SplitText, Len(SplitText) - _
InStr(SplitText, Delimiter))
Else
arr(iCounter) = SplitText
SplitText = ""
End If
iCounter = iCounter + 1
Loop
fncSplit = arr
End Function