I have 100 plus different users that will use a certain program that will require different settings in a ini file. I was thinking that excel might be the best way to create these files and write them to a folder in individual files. The data should look like this.
All of this data will need to be in every text file:
UseMct=
UseCellular=
UseKvh=
UseIridium=
UseAurora=
UseSailor=
SailorUnitAddress=
AuroraUnitAddress=
QualcommSerialPort=
MctUnitAddress=
CellularUnitAddress=
KvhSerialPort=
KvhUnitAddress=
IridiumUnitAddress=
IridiumPositionUrl=
HostUrl=
The individual values for each of the following columns will have the required data. so Cell B1 will have the value for the first text file where the above data will be in column A.
UseMct=(value in B1)
UseCellular=(value in B2)
etc, etc.
The next text file will have all of these fields in A1 once again, but with this field mapping.
UseMct=(value in C1)
UseCellular=(value in C2)
etc, etc.
This would loop until the document is completed and would use a certain field as the filenames. Need help! Thanks.
I have looked at the following questions:
Outputting Excel rows to a series of text files
Write each Excel row to new .txt file with ColumnA as file name
You need something like this:
Sub iniCreate()
For iCol = 1 To 3
Open Environ("UserProfile") & "/MyProg" & Range("B1").Offset(0, iCol - 1).Value _
& ".ini" For Output As #1
For jRow = 1 To 16
Print #1, Range("A2").Offset(jRow - 1, 0); Range("A2").Offset(jRow - 1, iCol)
Next jRow
Close #1
Next iCol
End Sub
I used random numbers as data so it looked like this:
V000 V001 V002
UseMct= 0.659099708 0.098897863 0.66830137
UseCellular= 0.081138532 0.064777691 0.919835459
UseKvh= 0.942430093 0.872116053 0.032414535
UseIridium= 0.263586179 0.921751649 0.295967085
UseAurora= 0.867225038 0.094161678 0.11271394
UseSailor= 0.112345073 0.247013614 0.562920243
SailorUnitAddress= 0.641083386 0.630124454 0.430450477
AuroraUnitAddress= 0.133569751 0.431081763 0.620952387
QualcommSerialPort= 0.489904861 0.745152668 0.0371556
MctUnitAddress= 0.390312141 0.643551357 0.621789056
CellularUnitAddress=0.924394826 0.672907813 0.834973453
KvhSerialPort= 0.431335182 0.040557434 0.329205484
KvhUnitAddress= 0.018331225 0.405080112 0.281003
IridiumUnitAddress= 0.530083065 0.428947849 0.781832847
IridiumPositionUrl= 0.473567159 0.428633715 0.00044413
HostUrl= 0.132253798 0.832369002 0.981755331
The V000, V001 etc form part of the file name. E.g. MyProgV000.ini
I use the UserProfile environment variable to select an output folder. You can choose another one if you prefer.
Then the two For Loops just output the data to the file.
Related
My CSV file:
Product Code,Product Description,Net Weight,POR Number,BBE Info (DD/MM/YY)
0001450,Californian Whole Almonds,22.68kg,POR17195,21/11/19
Excel file, when importing the CSV file.
Question
I'd like to place the POR Number column to the left of Product Code. But when I refresh the data, it goes back to it's original place.
How can I load the CSV file into excel and choose which column loads up where? Without adjusting the CSV structure.
Here is a desired output when I refresh the CSV data:
Read the file line by line and use split to split the columns and then output the data where you need.
Use application.OnTime to run the code every minute.
Make NextRun a global date variable
sub split_csv()
File = FreeFile()
Open "csv.csv" For Input As #File
i = 2
While Not EOF(File)
Line Input #File, csvLine
cols = split(csvLine, ",")
range("A" & i).value = cols(1) ' and so on...
i = i+1
Wend
NextRun = Now + timevalue("00:01:00")
Application.OnTime EarliestTime:=NextRun, Procedure:="split_csv", Schedule:=True
end sub
To stop the code from running you have to use Application.OnTime EarliestTime:=NextRun, Procedure:="split_csv", Schedule:=False, I'll advice you to add that to workbook_close or if you forget to turn off the function it will open the workbook again and keep going.
you can use the integrated feature Get & Transform (Excel 2016) or earlier Version with the MS Power Query Add-in.
Go to Data > New Query > From File > From CSV
Select your csv file. Click Import.
A preview of the csv data will be shown. Click Edit.
Go to Home > Transform > Use First Row As Headers
Move the column you want with drog & drap over the column header
you may remove some columns with right click on the column header
Give it a try. The UI is very intuitive and you don't have to write any code for most transforming tasks.
I have a problem with a select file window popping up while updating a link to an excel file. I believe it's caused by the destination file being saved at the moment I refresh the link.
I have 2 computers. I open file "A" on the first one and file "B" on the other.
File "A" runs this macro:
application.enableevents = false
Do until(I set loop for couple minutes )
Range("a1").value = 1
save
range("a1).value = 2
save
Loop
File B runs this macro:
range("b2").value = (link to File A, cell "a1")
z = 1
do until (runs for couple minutes)
Cells(z,1).value = range("b2").value
z = z+1
loop
So basically the first file continuously changes the value of cell "a1" between 1 and 2, and saves each time, while the second one constantly refreshes the link and records the linked cell value.
It works for a few rounds, then a select file window pops up.
Exact formula for the cell containing link:
"='[" & BAZAO.Name & "]" & "ZMIANY'" & "!a1"
And in excel cell it looks like that:
„='[BWP 215.xlsm]ZMIANY'!a1”
The line of code that refreshes the link:
BAZA.UpdateLink (BAZAZ.Range("C3").Value)
BAZA - name of FILE B
BAZAZ.range("c3").value - contains address and name of file A
Range("b2").value = "='[" & BAZAO.Name & "]" & "ZMIANY'" & "!a1"
„='[BWP 215.xlsm]ZMIANY'!a1”
Can anyone tell me how to suppress this select file window, or if there is any other workaround?
I think it's happening because when opening the excel file, excel creates it's copy with generated name. When changes are being saved and the original file replaced, excel deletes original file first, and then puts a temporary file in its place changing name to the original one.
I guess the select file window pops up when my macros hit between that moments.
Is this the cause?
I think I have found a workaround.
Instead of using a cell to track file avaliability I have made the code to create file "inuse.txt" in the "file A" directory whenever its in use.
Then the "file B" just checks if that file is present through dir command
I am reading a .csv database in excel, because I am using an external database.
I dont want to copy anything into the excel application, I either want to read from the database(and maybe change some values), or add to it.
I have a textbox in a userform that should get the value of the last entry in "column" A(A reference number), and add one to it(this is for the next entry in the database).
I want to find the last row in a semicolon split CSV database using excel VBA.
Here is what I have so far:
Dim FilePath As String
FilePath = "L:\database.csv"
Open FilePath For Input As #1
Do While Not EOF(1)
linenumber = linenumber + 1
Line Input #1, Line
arrayOfElements = Split(Line, ";")
elementnumber = 0
testValue = arrayOfElements(0)
If testValue = "L51599" Then
refnr.Text = testValue
Else
'do nothing
End If
Loop
Close #1
Any tips?
Thanks
There are 5 different ways to that here : http://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba.
Be aware of the fact that CSV files are not excel files and they cannot contain custom VBA functions (Macros). You will have to create your "findLastRow" function in a global template and assign it to a custom button on one of the toolbars/ribbons. this is explained here : https://msdn.microsoft.com/en-us/library/office/ee767705(v=office.14).aspx.
good luck!
I have a large text file exported from an application that has three unwanted zeros in each row. The text file needs to be imported into another application and the zeros cause a problem.
Basically the unwanted three zeros per row need to be deleted. These zeros are always in the same location (same number of characters when counting from the left), but the location is somewhere in the middle. I have tried various things like importing the file into excel, removing the zeroes and then exporting as text file, but always have formatting problems with the exported text file.
Can someone suggest a solution or point me in the right direction?
something like this ? (quickly done)
Sub replaceInTx()
Dim inFile As String, outFile As String
Dim curLine As String
inFile = "x:\Documents\test.txt"
outFile = inFile & ".new.txt"
Open inFile For Input As #1
Open outFile For Output As #2
Do Until EOF(1)
Line Input #1, curLine
Print #2, Replace(curLine, "000", "", 6, 1, vbTextCompare)
Loop
Close #1
Close #2
End Sub
Alternatively, you can do that with any text editor that allows block selection (I like Notepad2, tiny, fast and portable)
I see you use excel a lot.
When you import the text file into excel do you use the import function and do you push the data into separate cells?
if the cell is numeric you could do the following:
=LEFT(TEXT(G5,"#"),LEN(TEXT(G5,"#"))-3)
if the cell is text:
=LEFT(G5,LEN(G5)-3)
G5 would the cell the data row/field is in.
curLine = Left(curLine, 104)
This will take the first 104 characters
My Excel VBA worksheet creates logs in a directory. Currently, the logs keep building up as I do not remove them.
However, now I would like to only keep the most recent 5. My logs are created with filenames as below:
<worksheet_name>_YYYYMMDD_HH_MM_SS.log
My current method of doing this job is to throw these logs into an array, sort the array, and keep only the first 5.
My question is this: Does anyone have a better method of keeping only the most 5 recent log files?
That sounds like a workable solution. Use the FileSystemObject library to gather all the log files, then loop thru them.
One option: you could try deleting based on Date Created or Date Modified, i.e. if the file was created over x days ago, delete it.
Also, I don't know how important these files are, but you may want to just move them to a folder called Archive instead of outright deleting them.
One system we used a while ago was to keep e.g. 5 log files with a "gap". So you would create the first 5 log files:
Files: 1,2,3,4,5
Then, on the 6th day, your gap is at 6, so create 6 and delete 1
Files: ,2,3,4,5,6
The gap is now at 1. So for the next day, create 1, and delete 2
Files: 1, ,3,4,5,6
The gap is now at 2. So for the next day, create 2, and delete 3
Files: 1,2, ,4,5,6
etc etc
i.e. "Find the Gap" *, fill it with the new file, then delete the one after it.
Just an idea.
_* (yes this is a bad joke referring to the London Underground)
Even though this is an old question, since I needed this exact solution I figured I would add it here. This code assumes that the file name ends in something that is sortable by string comparison, so that could be files of a format SomeName_YYYY-MM-DD. Twenty-four hour time stamps can be incorporated as well. This process does not rename any files, so any incremental numeric scheme will need to be carefully managed by other code (i.e. you want to add _1, _2, etc. to the file names).
Note that this solution leverages collections which serve this purpose much better than an array.
Public Sub CleanBackups(filePathAndBaseName As String, fileExtension As String, maxCopiesToKeep As Integer)
'
' Calling Example
' CleanBackups "C:\Temp\MyLog", ".txt", 5
'
' The above example would keep only the 5 versions of the file pattern "C:\Temp\MyLog*.txt"
' that are "LARGEST" in terms of a string comparison.
' So if MyLog_1.txt thru MyLog_9.txt exist, it will delete MyLog_1.txt - MyLog_4.txt
' and leave MyLog_5.txt - MyLog_9.txt
' Highly recommend using pattern MyLog_{YYYY-MM-DD_HhNn}.txt
Dim pathOnly As String
Dim foundFileName As String
Dim oldestFileIndex As Integer
Dim iLoop As Integer
Dim fileNameCollection As New Collection
pathOnly = Left(filePathAndBaseName, InStrRev(filePathAndBaseName, "\"))
foundFileName = Dir(filePathAndBaseName & "*" & fileExtension, vbNormal)
Do While foundFileName <> ""
fileNameCollection.Add foundFileName
foundFileName = Dir
Loop
Do While fileNameCollection.Count > maxCopiesToKeep
' Find oldest file, using only the name which assumes it ends with YYYY-MM-DD and optionally a 24-hour time stamp
oldestFileIndex = 1
For iLoop = 2 To fileNameCollection.Count
If StrComp(fileNameCollection.Item(iLoop), fileNameCollection.Item(oldestFileIndex), vbTextCompare) < 0 Then
oldestFileIndex = iLoop
End If
Next iLoop
Kill pathOnly & "\" & fileNameCollection.Item(oldestFileIndex)
fileNameCollection.Remove oldestFileIndex
Loop
End Sub