VBA: File name and path as variables - excel

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

Related

Print Text File to Excel Sheet

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.

Use VBA to open .tbl file in notepad

I'd like to use VBA to open a .tbl file in notepad (or notepad++). Basically, I have some .tbl files that I can drag and drop into notepad++ to edit, and I'd like to do that same thing through VBA. I can take care of the editing once the file is open. I just can't find anything about opening a non-txt file in notepad using VBA.
Opening in Excel destroys the formatting, so I'd like to stick with a text editor.
Thanks!
You can write a simple VBA module that invokes Notepad++:
Sub Button1_Click()
Dim res As Variant
Dim fileToOpen As String
Dim nppPath As String
fileToOpen = "F:\test.tbl"
nppPath = "F:\Program Files (x86)\Notepad++\notepad++.exe"
res = Shell(nppPath & " " & fileToOpen, vbNormalFocus)
End Sub
I don't have sufficient reputation to comment on Andrea's code (which works for me). I did want to point out one thing for the benefit of others. I encounter an error using Andrea's code unless I put in a space after .exe ". Other than that small observation mine adds nothing to Andrea's answer.
Sub OpenInNotepadPP()
Dim FullFilePath As String
FullFilePath = "C:\FilePath\FileName.txt"
Dim MyTxtFile As Variant
'Note, a single space needs to be placed after notepat++.exe "
MyTxtFile = Shell("C:\Program Files (x86)\Notepad++\notepad++.exe " & FullFilePath, vbNormalFocus)
End Sub

VBA: Line Input #, next file not showing new data

I'm reading multiple csv files into excel for some number crunching. The file reads appear to work with each excel column having the csv file name inserted for confirmation. Odd thing. Each csv file name is correctly inserted into the sheet, but the data is all the same as the first file.
Is there a way to flush / reset ..... something, so the next read file data actually is the next file?
Excel VBA code snippet:
Public Const sRawFilePath As String = "\\server1\Sample.RAW.Files\"
----------------
Sub ImportCSV()
Dim sFullFilePath, sFile As String
fFIle = FreeFile()
sFile = Dir(sRawFilePath & "*.csv")
sFullFilePath = sRawFilePath & sFile
While sFile <> ""
Open sFullFilePath For Input As fFIle
While Not EOF(fFIle)
Line Input #fFIle, sLine
""
"take the sLine string and separate the comma delimited values for insertion into columns "
"This part works fine"
""
Wend
Close fFIle
sFile = Dir()
Wend
End Sub
Stepping through the code I can confirm the next file is in the queue, but the read data is not representing the next file, just the first file, ... and always the first file even though 20 more files are read.
PS - This forum has been an amazing resource.
The problem is you define sFullFilePath which locks in the file that you're opening. So even though you're successfully looping through the files with Dir, you will only open the first one because you locked it in. Don't use that variable at all:
'Change this line
Open sFullFilePath For Input As fFIle
'To be this instead
Open sRawFilePath & sFile For Input As fFIle
Rather than executing Dir(sRawFilePath & "*.csv") in every call, you should just execute Dir in subsequent calls. The error causes you to re-read the first file again and again.

How can I take non-ASCII strings from an Excel cell and place them into a text file (JSON format) with proper encoding?

We are writing a very basic macro for an Excel file that takes values from cells and places them into a text file with a JSON format. We are using the Range function to extract the cell values like this:
Print #iFile, " ""title"": """ & Range("AP" & cell.Row).Value & """"
I'm sure this isn't the prettiest or most efficient approach, but it seems to work for our purposes (and to be perfectly honest, we don't have anyone on hand that is actually a VBA developer really...). The problem, though, is when we encounter foreign characters (Latin, Japanese, etc) that are not being picked up by the VBA code above whatsoever.
What we would like to do is not only extract the string from the cell no matter what type of characters are in there (ASCII or otherwise), and place them into the text file with any necessary encoding on the string values such that the file will still contain valid JSON.
Any help with this issue would be very appreciated as this is a subject that is far out of my comfort zone (front-end web development).
This should get you headed in the right direction
Public Sub SaveUnicodeCharacterInTextFile()
' Declare a FileSystemObject.
Dim fso As FileSystemObject
' Create a FileSystemObject.
Set fso = New FileSystemObject
' Declare a TextStream.
Dim stream As TextStream
' windows path name
wbPath = ActiveWorkbook.Path
' name the output file and path to save it to - same directory as the workbook
outFile = wbPath & "\outputfile.txt"
' Create a TextStream. Overwrite = true Unicode = True
Set stream = fso.CreateTextFile(outFile, True, True)
'Put a value in the stream - in this case we are simly pulling the value out of one cell
'You can certainly iterate through the worksheet
stream.Write (Range("A1"))
'close the stream
stream.Close
End Sub

error writing in file vba

I'm trying to write a file using VBA. My code is below. It worked the first time, but when i closed the excel file (.xlsm) and try to use it again, it doesn't work.
I do not get any errors when running the macro but the new file does not appear
Sub LogInformation(LogMessage As String)
Const LogFileName As String = "TEXTFILE.db"
Dim FileNum As Integer
FileNum = FreeFile ' next file number
Open LogFileName For Append As #FileNum ' creates the file if it doesn't exist
Print #FileNum, LogMessage ' write information at the end of the text file
Close #FileNum ' close the file
End Sub
Sorry guys. That was dumb.
The default relative path is in User/%MyUser%/Documents.
I need to use ChDir then open/write/close the file.
Chdir(ActiveWorkbook.Path)

Resources