The fix was simple. The old code had the following:
ReadPathName = MyPath + ReadFilename
Notice the path was included in the ReadPathName. GetSaveAsFilename was
also including the path. You had the path in the name twice. I simply
removed MyPath from ReadPathName.
I nthe code below I change your InitialFileName to include MyPath. Now the
Pop Up window goes to the MyPath directory (folder). The Pop up will return
the full pathname of the file which you can simply open.
There is a problem with some VBA file selection methods that you have to
strip the filename from the path to use them. I originally set the code up
keeping the path and the filename seperate so these functions can be used
(you don't have this problem yet). In the past, I've had to write a simple
loop to strip the file name from the path when using some of these commands.
It is just extra code that is unecessary.
Your code is just fine!
Sub advanceformat()
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const MyPath = "C:\temp\"
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim StartField(120)
ReadFilename = Application.GetSaveAsFilename( _
fileFilter:="Text Files, *.txt", _
InitialFileName:=MyPath & "FixedWidth.txt", _
Title:="SelectDataFile")
Set fsread = CreateObject("Scripting.FileSystemObject")
'open files
Set fread = fsread.GetFile(ReadFilename)
Set tsread = fread.OpenAsTextStream(ForReading, TristateUseDefault)
inputline = tsread.readline
Length = Len(inputline)
StartField(0) = 1
FieldCount = 1
Spaces = False
For ColumnCount = 1 To Length
Select Case Spaces
Case True
If Mid(inputline, ColumnCount, 1) <> " " Then
StartField(FieldCount) = _
ColumnCount
FieldCount = FieldCount + 1
Spaces = False
End If
Case False
If Mid(inputline, ColumnCount, 1) = " " Then
Spaces = True
End If
End Select
Next ColumnCount
StartField(FieldCount) = Length + 1
OutputString = "Number of columns = " & _
Length & Chr(13)
For Fields = 0 To (FieldCount - 1)
MyWidth = StartField(Fields + 1) - _
StartField(Fields)
Cells(Fields + 1, "A") = "Field " & (Fields + 1)
Cells(Fields + 1, "B") = StartField(Fields)
Cells(Fields + 1, "C") = MyWidth
OutputString = OutputString & "Field " & _
(Fields + 1) & " start at " & _
StartField(Fields) & ", width = " & _
MyWidth & Chr(13)
Next Fields
MsgBox (OutputString)
tsread.Close
End Sub