Find last row in CSV database from Excel VBA - excel

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!

Related

How to load specific CSV column to the left in EXCEL?

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.

Working with Excel sheets in MATLAB

I need to import some Excel files in MATLAB and work on them. My problem is that each Excel file has 15 sheets and I don't know how to "number" each sheet so that I can make a loop or something similar (because I need to find the average on a certain column on each sheet).
I have already tried importing the data and building a loop but MATLAB registers the sheets as chars.
Use xlsinfo to get the sheet names, then use xlsread in a loop.
[status,sheets,xlFormat] = xlsfinfo(filename);
for sheetindex=1:numel(sheets)
[num,txt,raw]=xlsread(filename,sheets{sheetindex});
data{sheetindex}=num; %keep for example the numeric data to process it later outside the loop.
end
I 've just remembered that i posted this question almost 2 years ago, and since I figured it out, I thought that posting the answer could prove useful to someone in the future.
So to recap; I needed to import a single column from 4 excel files, with each file containing 15 worksheets. The columns were of variable lengths. I figured out two ways to do this. The first one is by using the xlsread function with the following syntax.
for count_p = 1:2
a = sprintf('control_group_%d.xls',count_p);
[status,sheets,xlFormat] = xlsfinfo(a);
for sheetindex=1:numel(sheets)
[num,txt,raw]=xlsread(a,sheets{sheetindex},'','basic');
data{sheetindex}=num;
FifthCol{count_p,sheetindex} = (data{sheetindex}(:,5));
end
end
for count_p = 3:4
a = sprintf('exercise_group_%d.xls',(count_p-2));
[status,sheets,xlFormat] = xlsfinfo(a);
for sheetindex=1:numel(sheets)
[num,txt,raw]=xlsread(a,sheets{sheetindex},'','basic');
data{sheetindex}=num;
FifthCol{count_p,sheetindex} = (data{sheetindex}(:,5));
end
end
The files where obviously named control_group_1, control_group_2 etc. I used the 'basic' input in xlsread, because I only needed the raw data from the files, and it proved to be much faster than using the full functionality of the function.
The second way to import the data, and the one that i ended up using, is building your own activeX server and running a single excelapplication on it. Xlsread "opens" and "closes" an activeX server each time it's called so it's rather time consuming (using the 'basic' input does not though). The code i used is the following.
Folder=cd(pwd); %getting the working directory
d = dir('*.xls'); %finding the xls files
N_File=numel(d); % Number of files
hexcel = actxserver ('Excel.Application'); %starting the activeX server
%and running an Excel
%Application on it
hexcel.DisplayAlerts = true;
for index = 1:N_File %Looping through the workbooks(xls files)
Wrkbk = hexcel.Workbooks.Open(fullfile(pwd, d(index).name)); %VBA
%functions
WorkName = Wrkbk.Name; %getting the workbook name %&commands
display(WorkName)
Sheets=Wrkbk.Sheets; %sheets handle
ShCo(index)=Wrkbk.Sheets.Count; %counting them for use in the next loop
for j = 1:ShCo(index) %looping through each sheet
itemm = hexcel.Sheets.Item(sprintf('sheet%d',j)); %VBA commands
itemm.Activate;
robj = itemm.Columns.End(4); %getting the column i needed
numrows = robj.row; %counting to the end of the column
dat_range = ['E1:E' num2str(numrows)]; %data range
rngObj = hexcel.Range(dat_range);
xldat{index, j} = cell2mat(rngObj.Value); %getting the data in a cell
end;
end
%invoke(hexcel);
Quit(hexcel);
delete(hexcel);

Removing unwanted data from text file

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

Retrieving last line of a txt file with a VBscript

Before all, I want to say that I am not a programmer, so this may be basic for some people but surely not for me!!
The task that I want to accomplish is to retrieve some characters of a data file that is imported automatically from a server.
Data is stored in lines in a CSV or tabbed .txt file, each line consists of date and some numeric values. The format is always the same, only the file grows in one line each time a new value is entered.
What I need the script to do, is open that file (wich adress is known and constant) search for the last line, and then extract a string from that line and write it on a different .TXT file, from where I can import it to another specific software as a raw value.
The part in the middle (extracting string) is fairly simple, but opening and isolating the last line is far too much for me.
Thanks everybody for helping!
dim path
path = "fileName.txt"
otherOption(path)
function otherOption(fileName)
const read = 1
dim arrFileLines()
set objArgs = CreateObject("scripting.FileSystemObject")
if objArgs.FileExists(fileName) then
set objFile = objArgs.OpenTextFile(fileName,read)
i=0
do until objFile.AtEndOfStream
redim preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
loop
objFile.Close
end if
wscript.Echo arrFileLines(i-1)
end function

Best way to write multiple .ini files

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.

Resources