Convert CSV file to MS-Word Table document
Code:
Sub UseCSV2WordTableDoc()
CSV2WordTableDoc "C:\!Tools\0001.txt"
End Sub
Public Sub CSV2WordTableDoc(sCSVFilePath As String)
'-- Notes: This Sub won't take care of Text field qualifier in CSV file,
'-- such as ", that will be treated as a normal character
Const wdSeparateByCommas = 2
Const wdAutoFitFixed = 0
Dim wdApp As Object
Dim wdDoc As Object
Dim sTemp As String
Dim i As Long
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If wdApp Is Nothing Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo CSV2WordTableDoc_Error
If wdApp Is Nothing Then
MsgBox "Cannot Open Microsoft-Word", vbExclamation, "Error!"
Exit Sub
End If
wdApp.Visible = True
'Open sCSVFilePath For Input As #1
'sTemp = Input(LOF(1), #1)
'Close #1
'Set wdDoc = wdApp.Documents.Add
'-- EDIT: instead of using 4 lines above, the file can be opened directly with Word:
Set wdDoc = wdApp.Documents.Open(sCSVFilePath)
'--
wdDoc.Range.InsertAfter sTemp
wdDoc.Range.ConvertToTable Separator:=wdSeparateByCommas, _
AutoFitBehavior:=wdAutoFitFixed
i = InStrRev(sCSVFilePath, ".")
If i <= InStrRev(sCSVFilePath, "\") Then
sTemp = sCSVFilePath & ".doc"
Else
sTemp = Left$(sCSVFilePath, i) & "doc"
End If
wdDoc.SaveAs sTemp
CleeanUp:
Set wdDoc = Nothing
Set wdApp = Nothing
Exit Sub
CSV2WordTableDoc_Error:
MsgBox "Runtime Error " & Err.Number & vbCrLf & Err.Description, _
vbCritical, "CSV2WordTableDoc Error!"
Resume CleeanUp
End Sub
Re: Convert CSV file to MS-Word Table document
Hi
I've just picked up on this thread and have had a go at inserting the csv file into the "current document" - how would amend the code above to achieve this as my attempts have failed.
Would really appreciate an answer to this.
Cheers
Phil