Print Text File to Excel Sheet - excel

I have a text File named "amk.txt" which looks inside like:
Test Number 1234
sampleCounter 123
Time Speed[km\h]
1 12
2 13
3 14
4 15
I need to print the content to Excel Sheet by using VBA. I have a Function to read the content of the file and to save the content into an Array. The Array looks inside like this:
TestNumber1234
sampleCounter123
TimeSpeed[km\h]
112
213
314
415
My Problem is, that the array which saves the fileContent does not look like the inside of txt file.
So I have to questions:
makes it sense to save the file content to a array or to print it directly into the excel sheet?
If I want to save it into the array, why does the array not look like the text file?
I wrote two different Functions to save the file content into a array
First Function:
Public Function read_file_with_FSO(fileName)
Const ForReading=1
Set fileObject = CreateObject("Scripting.FileSystemObject")
Set file= fileObject.OpenTextFile(fileName, ForReading)
fileContentFSO=Split(f.readAll,vbNewline)
read_file_with_FSO=fileContentFSO
End Function
Second Function:
Public Function read_file(fileName)
index=0
Open fileName For Input as #1
Line Input #1, textline
fileContent(index)=textline
index=index+1
Loop
Close #1
read_file=fileContent
End Function

Try following code to load the file to excel:
Sub Load_text_file()
Dim strFilename As String, strLine As String, strSprt As String
Dim lngRows As Long
strFilename = Application.GetOpenFilename("Text files, *.txt") ' you may replace this with direct path to your file. NOTE there is no handler for "Cancel" button here - so there will be an error if you press it
Open strFilename For Input As #1
lngRows = 1
Do While Not EOF(1)
Line Input #1, strLine
ActiveSheet.Cells(lngRows, 1) = strLine ' !!! replace an ActiveSheet with your sheet's name
lngRows = lngRows + 1
Loop
Close #1
End Sub
Then go to Excel, select the copied data, go to Data tab, press the Text to Columns button. On the first step select "Delimited" and press next. On the second step - try selecting different delimiters, unless you see that Excel splits text to columns using one of them:
If you find delimiter in you file (usually it is the Tab, Comma or Semicolon) then you can add following code to the sub above:
With ActiveSheet ' !!! replace an ActiveSheet with your sheet's name
range(.Cells(1, 1), .Cells(lngRows - 1, 1)).TextToColumns Destination:=.Cells(1, 1), Tab:=True ' In my case the delimiter is Tab, so set it to true, when you start typing editor will suggest parameters. If you'd like to use other character - you will need to set also that char: other:=True, otherchar:="|"
End With
If this doesn't help - you may need to change your text file format or create some sub or function to get your text formatted properly in Excel.
Try the code, read comments, ask if something is not clear.

The array you have is each line in the file.
Since it's a text file with tabs you may be able to read & paste the contents all in to cell A1 and because of the tabs it will fill out across multiple lines and tab delimited columns.
Range("A1").Select
ActiveSheet.Paste
Or
Range("A1").PasteSpecial Paste:=xlPasteFormats
You can google how to use the VBA clipboard, to save what's already in the clipboard, set the file contents to clipboard, then do the paste command above and finally restore whatever the user previously had in their clipboard.
    
The 2nd screenshot looks like the VBEditor Watch window and that's showing each line as an array item. You could iterate through the array, using Split to get elements and in a nested loop lay them out.

Related

VBA: File name and path as variables

I'm super green/new to VBA.
I've got a file location that I enter in on Sheet 4. That reads in fine.
Then I've got a file name using the DIR function, again that's fine.
Now I want to Open my file, however I can't get it to work this way. I can't hard code the file name (it's too long).
There's got to be a simple way to do this. I've seen some examples but they look way too complicated, it's got to be like 2 lines max from what I've got.
Any thoughts?
Sub data_import_new()
'
' data_import_new Macro
Dim File_Location As String
Dim File_Name As String
Dim text As String
File_Location = Sheet4.Cells(3, 5).Value
File_Name = Dir(Residual_File_Location & "\*.txt")
Open Residual_File_Name For Input As #1
Input #1, text
MsgBox text
Close #1
End Sub

Print string to file, only parts of the string got printed

I've made an application where users write stuff in Excel cells and that info is then printed to a .txt file.
The info is concatenated into a long string before printing it into the file.
The info is not stored in the Excel sheet. Every time you open the sheet, it loads the info from the .txt file into the different cells. If a user changes the content of a cell the info is then printed to the .txt file. Multiple people are working at the same time, changing the cells. Everyone has got their own version of the empty workbook, where the data loads when the workbook is opened. And when someone changes a cell, the data is printed to the .txt file and is then everyone who is working with the application is reading from the file and getting that cell updated with the new info.
Now, someone copied the content of a cell into another cell and hit Enter (which triggers the concatenation process and stores it into the .txt file) What happened was that all the info after the new info didn't get printed. So the last 30000 characters or so just got lost. I'm thinking the user accidentally copied a character with a special meaning like "Stop reading and print to file" or something. But does characters like that exists? Do you have any clue what might have happened?
This is the code that concatenates the string:
Line = ProjectsArray(0) 'Line is the long string that gets printed to the text file
ProjectsArray(ProjectsArrayPosition) = ProjectNumber 'ProjectsArray is string 'Line' but split into the different projects
'ProjectInfo is a specific project split into its different data points. (Every data point belongs to a Excel cell)
'ProjectsArrayPosition is the place in the array where the current Project lives.
'Every data point is joined with a chr(17) in between.
For i = 1 To UBound(ProjectInfo)
ProjectsArray(ProjectsArrayPosition) = ProjectsArray(ProjectsArrayPosition) & Chr(17) & ProjectInfo(i)
Next i
If UBound(ProjectsArray) > 0 Then
For i = 1 To UBound(ProjectsArray)
Line = Line & Chr(18) & ProjectsArray(i) 'Every project is joined with a chr(18) in between
Next i
End If
On Error GoTo NoPath
Open ProjectsFilePath For Output As #1
Print #1, Line
Close #1
On Error GoTo 0
Here's the code that opens the array:
On Error GoTo NoPath
Open ProjectsFilePath For Input As #1
Line Input #1, Line
Close #1
On Error GoTo 0
ProjectsArray = Split(Line, Chr(18))
For i = 1 To UBound(ProjectsArray)
If CInt(Left(ProjectsArray (i), 6)) = ProjectNumber Then
ProjectInfo = Split(ProjectsArray(i), Chr(17))
ProjectsArrayPosition = i
End If
Next i
Select Case ActiveCell.Address
Case "$N$11"
For i = 0 To UBound(ProjectInfo)
If Left(ProjectInfo(i), 1) = "B" then
ProjectInfo(i) = "B" & Sht.Range("N11").Value
End If
Next i
Case "$G$18"
For i = 0 To UBound(ProjectInfo)
If Left(ProjectInfo(i), 1) = "F" then
ProjectInfo(i) = "F" & Sht.Range("G18").Value
End If
Next i
Case "$M$20"
And so on and so on
End Select
The code above is loaded every time you press Enter.
Private Sub Workbook_Activate()
Application.OnKey "~", "EnterPress"
Application.OnKey "{ENTER}", "EnterPress"
End Sub

VBA to open explorer and select, not open, a selected file name

I want a macro to open windows explorer and just select a file but don’t want it to open the file.
I’ve got a list of document names in excel split into some variables.
I also included some hyperlinks in it, so you can directly open the selected file.
But now I want a macro that selects the corresponding file in explorer and just selects it.
All files are in a predefined location, but all filenames are different, off course.
Example;
D:\username\Documents\workplans\document.001.1.xls
D:\username\Documents\workplans\document.002.2.xls
D:\username\Documents\workplans\document.003.3.xls
I want to select the corresponding file name in excel, and start the macro to select it in explorer.
So for example I select cell D3 and start the macro so it opens explorer and go’s to the following address and selects the file; D:\username\Documents\workplans\document.002.2.xls
A B C D E
1. var 1 var 2 var 3 doc. Name Hyperlink
2. document 1 1 document.001.1.xls document.001.1
3. document 2 2 document.002.2.xls document.002.2
4. document 3 3 document.003.3.xls document.003.3
If I use the following code directly to the link it works like how I want it to be, but the file name is variable.
Sub open_explorer()
Shell "C:\Windows\explorer.exe /select,D:\username\Documents\workplans\document.002.2.xls", vbMaximizedFocus
End Sub
I adjusted the code, but it won’t work. I think the problem is in the (& range (activeCell.select)).
How do I get this to work?
Sub open_explorer()
Shell "C:\Windows\explorer.exe /select, D:\username\Documents\workplans\ &Range ActiveCell.Select", vbMaximizedFocus
End Sub
Give this a try:
Sub open_explorer()
Shell "C:\Windows\explorer.exe /select, ""D:\username\Documents\workplans\" _
& ActiveCell.Value & """", vbMaximizedFocus
End Sub
Note that quotes are required around any path that has spaces or other special characters. The doubled quotes in the string above, both before D: and after ActiveCell.Value (concatenated to the end of the string) puts a double quote char before and after the path.
The above only worked for me if I add an extension to the filename such as ".xls".
Sub open_explorer()
Shell "C:\Windows\explorer.exe /select, D:\username\Documents\workplans\" & ActiveCell.Value & ".xls", vbMaximizedFocus
End Sub

Exporting text from from multiple Excel files to a single comma delimited file

I need to export data from Excel to a comma delimited file. I am using a button that runs a macro that creates the text file in a location I specify and exports values.
But, I want to copy this Excel with the same macro, and add different values. When I run the macro in the copied Excel file I want the same text delimited file to add these values under the previous set of values, not overwrite the values from the first Excel file.
How is this possible? I want to use the same text file each time.
Append using following routine:
Sub writeCSV(ByVal thisRange As Range, ByVal filePath As String, _
Optional ByVal fileAppend As Boolean = False)
Dim cLoop As Long, rLoop As Long
Dim ff As Long, strRow As String
ff = FreeFile
If fileAppend Then
Open filePath For Append As #ff
Else
Open filePath For Output As #ff
End If
For rLoop = 1 To thisRange.Rows.Count
strRow = ""
For cLoop = 1 To thisRange.Columns.Count
If cLoop > 1 Then strRow = strRow & ","
strRow = strRow & thisRange.Cells(rLoop, cLoop).Value
Next 'cLoop
Print #ff, strRow
Next 'rLoop
Close #ff
End Sub
Example usage
writeCSV sheet1, "c:\test.txt", true
It is easy to do it by using a StreamWriter. The AppendText function of the FileInfo class returns one that is configured for appending text to an existing file.
I write my example as pseudo code, as I don't know how you are retrieving the information from Excel. The File handling part, however, is complete:
Dim file As New FileInfo("C:\myOuputFile.csv")
Using writer = file.AppendText()
While isRowAvailable
writer.WriteLine("Write next row")
End While
End Using
The Using statement automatically closes the file at the end.

Export Excel stylesheet to CSV with comma separated and cells with text format in double quotes

Example - Source:
ID NAME TEXT
01 John Lore ipsum..
In this case all cells have format General and Lore ipsum.. text have format Text
And I want export this excel stylesheet to csv with comma separated and lore ipsum.. text with double quotes, something like this:
ID,NAME,TEXT
01,John,"Lore ipsum.."
Might not be exactly as asked, however this is what worked best for me:
Save the CSV in Excel normally (File > Save As > CSV (Comma separated))
Open a powershell window where the exported CSV is
Run this command (considering the CSV file was named "Book1.csv":
import-csv -path .\Book1.csv -Delimiter ";" | export-csv -path .\Book1_comma.csv -Delimiter ","
The following Microsoft article details the procedure you're looking for; http://support.microsoft.com/kb/291296 In the spirit of SO, I'll summarise here.
In Excel (I'm using 2003), navigate to Tools > Macro > Visual Basic Editor. That will launch the editor in a new window.
Next you want Insert > Module. In that window, paste the VB code, as follows:
Sub QuoteCommaExport()
' Dimension all variables.
Dim DestFile As String
Dim FileNum As Integer
Dim ColumnCount As Integer
Dim RowCount As Integer
' Prompt user for destination file name.
DestFile = InputBox("Enter the destination filename" _
& Chr(10) & "(with complete path):", "Quote-Comma Exporter")
' Obtain next free file handle number.
FileNum = FreeFile()
' Turn error checking off.
On Error Resume Next
' Attempt to open destination file for output.
Open DestFile For Output As #FileNum
' If an error occurs report it and end.
If Err <> 0 Then
MsgBox "Cannot open filename " & DestFile
End
End If
' Turn error checking on.
On Error GoTo 0
' Loop for each row in selection.
For RowCount = 1 To Selection.Rows.Count
' Loop for each column in selection.
For ColumnCount = 1 To Selection.Columns.Count
' Write current cell's text to file with quotation marks.
Print #FileNum, """" & Selection.Cells(RowCount, _
ColumnCount).Text & """";
' Check if cell is in last column.
If ColumnCount = Selection.Columns.Count Then
' If so, then write a blank line.
Print #FileNum,
Else
' Otherwise, write a comma.
Print #FileNum, ",";
End If
' Start next iteration of ColumnCount loop.
Next ColumnCount
' Start next iteration of RowCount loop.
Next RowCount
' Close destination file.
Close #FileNum
End Sub
Next you'll need to highlight the cells in your spreadsheet that you want to export. Once they've been selected, Run your macro against them. Specify a path to save your file to, and you're done.
Full credits to the author of the article at Microsoft, http://support.microsoft.com/kb/291296.

Resources