I have an issue I hope you can assist me with.
I need to copy 5 files into one, the challenge though is the files is named after the dates they were created.
eg. file names could be;
TTDU 20191113 (for today).
TTDU 20191112
TTDU 20191111
etc.
(TTDU is name of the report and will never change)
Is there a way to create a line of code, where it subtracts -1 day from file name? And can it work for workdays and not include weekend?
Or maybe you have an idea how to do it in another way
Thanks a lot!
Something along these lines, using split and mid
Called like so
SortDateOut("TTDU 20191123")
Function SortDateOut(strInput As String) As Date
Dim s As String
s = Split(strInput, Chr(32))(1)
SortDateOut = DateSerial(Mid(s, 1, 4), Mid(s, 5, 2), Mid(s, 7, 2))
End Function
Related
I have roughly 70,000 sheets that all have to have calculations done, and then all results compiled into a new sheet (which would be 70,000 lines long).
It needs to be sorted by date.
I'm VERY very very poor at matlab, but I've what I need the script to do for each excel sheet, I'm just unsure how to make it do them for all.
Thank you!!! (I took out some of the not important code)
%Reading in excel sheet
B = xlsread('24259893-008020361800.TorqueData.20160104.034602AM.csv');
%Creating new matrix
[inYdim, inXdim] = size(B);
Ydim = inYdim;
[num,str,raw]=xlsread('24259893-008020361800.TorqueData.20160104.034602AM.csv',strcat('A1:C',num2str(Ydim)));
%Extracting column C
C=raw(:,3);
for k = 1:numel(C)
if isnan(C{k})
C{k} = '';
end
end
%Calculations
TargetT=2000;
AvgT=mean(t12);
TAcc=((AvgT-TargetT)/TargetT)*100 ;
StdDev=std(B(ind1:ind2,2));
ResTime=t4-t3;
FallTime=t6-t5;
DragT=mean(t78);
BreakInT=mean(t910);
BreakInTime=(t10-t9)/1000;
BreakInE=BreakInT*BreakInTime*200*.1047;
%Combining results
Results=[AvgT TAcc StdDev ResTime FallTime DragT BreakInT BreakInTime BreakInE]
I think I need to do something along the lines of:
filenames=dir('*.csv')
and I found this that may be useful:
filenames=dir('*.csv');
for file=filenames'
csv=load(file.name);
with stuff in here
end
You have the right idea, but you need to index your file names in order to be able to step through them in the for loop.
FileDir = 'Your Directory';
FileNames = {'Test1';'Test2';'Test3'};
for k=1:length(FileNames)
file=[FileDir,'/',FileNames{k}]);
[outputdata]=xlsread(file,sheet#, data locations);
THE REST OF YOUR LOOP, Indexed by k
end
How you choose to get the file names and directory is up to you.
Quick question that should be easy enough for a lot of you but I'm not well versed in VBA or code in general for that matter but I have a problem that only a Macro or piece of VBA code can resolve for me. I have to edit a large number of data entries in a spreadsheet, cell by cell.
So on to the question. Could you please show me an example or provide a complete macro for me to use to edit these cells?
The editing that I require is as follows:
I need to read each cell in the following range: B2 to Q383. A typical entry that needs to be examined and edited looks like this: 629.64\3.00\01:30
What needs to happen now is for everything to the left of the first "\" and everything to the right of the second "\" needs to be removed, including the "\", from each cell.
I've tried fiddling around with the LEFT and RIGHT commands and I can output the data that needs to be removed from the cells with something like this
=left(B11, Find("\", B11) - 1)
So what would be the delete command in a macro to target that data selection in that cell? Or how do I use a delete command with those parameters?
Thanks in advance for any advice or answers!
Not 100% sure what you're after - you say you want to remove the bits from the left and right, but the formula returns the bit on the left.
Anyway, here's 3 formula to do it:
Left: =TRIM(LEFT(B11,FIND("\",B11)-1))
Middle: =LEFT(MID(B11,FIND("\",B11)+1,LEN(B11)),FIND("\",MID(B11,FIND("\",B11)+1,LEN(B11)))-1)
Right: =MID(B11,FIND("\",SUBSTITUTE(B11,"\","~",1))+1,LEN(B11))
And three VBA functions to do it
(use these as you would formula - =leftbit(B11), or if you're looking for something other than backslashes - =leftbit(B11,"|") will find the I-bar as a divider. )
Public Function LeftBit(target As Range, Optional Divider As String = "\") As String
LeftBit = Trim(Left(target, InStr(target, Divider) - 1))
End Function
Public Function MiddleBit(target As Range, Optional Divider As String = "\") As String
Dim First As Long, Second As Long
First = InStr(target, Divider)
Second = InStr(First + 1, target, Divider)
MiddleBit = Mid(target, First + 1, Second - First - 1)
End Function
Public Function RightBit(target As Range, Optional Divider As String = "\") As String
RightBit = Right(target, Len(target) - InStrRev(target, Divider))
End Function
I need to read or clear all the line in specific range which will be increasing dynamically.
Problem is "Selected File List" table range is not specified. New file chosen with browse will be added to "Selected File List" dynamically. Number of file can't be predicted.
What I've tried so far is, keep track of the browse button click and add the file path to arraylist.
After that, (Row number 9 which is start line + arraylist size) to get the number of line of end of the table.
But due to some requirement, I want to read the file from excel file. Something like -Read until found blank line or border bottom or something.
I'm new to VBA and I'm not so sure what I'm doing with vba codes so please be kind :D
Any input would be greatly appreciated. Thanks for your precious time.
Provided there is no blank cell within the list of files, you could give the heading cell ("Selected File List") a name, e.g. "SelFiles" and do something like this ...
Sub Test()
' call the function
Debug.Print getSize(Range("SelFiles"), True)
End Sub
Function getSize(MyRange As Range, Optional HasHeader As Boolean = False)
Dim Idx As Integer
Idx = 2
Do While MyRange(Idx, 1) <> ""
Idx = Idx + 1
Loop
If HasHeader Then
getSize = Idx - 2
Else
getSize = Idx - 1
End If
End Function
The function uses a bit of abstraction, you can use it for ranges including / excluding ranges. You may have other areas in your application where you need to count rows, so the use of a function is preferred to just adding the loop into the code of your main Sub().
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.
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