I have a text file and I'm trying to count the number of commas in the first line of the file using excel VB and then do an action if there are 3 - but something is wrong. When I use the replace method (commented out in this example below) the macro fails, and when I use the Split method it ALWAYS does the action, no matter what value I add in place of 3.
'Load txt file into array
Open FilePath For Input As #1
dataArray = Split(Input$(LOF(1), #1), vbLf)
Close #1
'Test first line if it has three commas
If Len(dataArray(0).value) - Len(Replace(dataArray(0).value, ",", "")) = 3 Then
'If dataArray(0).Split(",").Length = 3 Then
'Add comma to start of strings
For i = LBound(dataArray) To UBound(dataArray)
dataArray(i) = "," & dataArray(i)
Next i
The .value appears to be the problem. VBA doesn't have properties the same way .NET does.
Replace your uncommented out IF statement with this:
If Len(dataArray(0)) - Len(Replace(dataArray(0), ",", "")) = 3 Then
Related
I am working parallel with Excel and VBA in order to create txt files I wish to use for MATLAB. However, I experience some format issues I can't resolve.
For instance, the following VBA
Open "example.txt" For Output As #1
For i = 1 To 5
Print #1, Sheets("Example").Cells(i + 3, 3)
Next i
Indeed prints numbers (reals) it is supposed to however MATLAB struggles with reading this example .txt file.
There are some characters VBA is printing. I don't know how to delete those within a VBA code.
Example.txt opened in matlab. Note the NaN read by MATLAB from a text file:
VBA text file - Note a line as the first element of a column
Perhaps there is a character that is invisible.
A possible solution is to remove those characters with regex.
Add reference to Microsoft VBScript Regular Expression 5.5
Then the following VBA code:
Set re = New RegExp
re.Pattern = "[^0-9]"
Open "example.txt" For Output As #1
For i = 1 To 5
Print #1, re.Replace(Sheets("Example").Cells(i + 3, 3).value, vbNullString)
Next i
This should remove anything that is not a digit from the cell before printing it to the text document.
I'm trying to find the carriage return\line break in various cells, by iterating over them and running the InStr function against the text in each of those cells. The below query is finding the line break correctly in most cells, but is failing in one of those cells.
The line break in those cells was added the same for all of them, and that is by hitting Alt+Enter.
Below is the function I am using:
InStr(startlocation, text, vbLf)
I also tried all of the below, but to no avail:
InStr(startlocation, text, Chr(10)) 'this seems to be identical in results to using vbLf
InStr(startlocation, text, Chr(13)) 'No results with this
InStr(startlocation, text, ALT + 10) 'I see this returning some results sometimes, not exactly sure for which character though
InStr(startlocation, text, vbCrLf) 'No results with this
Is there any other way to represent line break so I add it to my query?
The line break in cells, which is created with Alt + Enter is a vbLf.
Therefore the following should work.
InStr(startlocation, text, vbLf)
If it doesn't work that means you did something else wrong.
If you have the following data in cell A1 (Alt + Enter after 1 and 2)
Then InStr(1, Range("A1"), vbLf) returns 2.
For example you can use …
Dim ArrLines As Variant
ArrLines = Split(Range("A1"), vbLf)
to split these lines into an array like …
ArrLines(0) is 1
ArrLines(1) is 2
ArrLines(2) is 3
As others have confirmed, vbLf was indeed the correct character for identifying the line break introduced by ALT + Enter. My issue turned out to be caused by how the content of text was ending one character before the line break, therefore the InStr(startlocation, text, vbLf) on that string was not finding the line break. Extending text (which was created using the Mid function) by 1 took care of the issue. So:
Instead of: text = Mid(entryvalue, delimeterlocation, Len(entryvalue) - delimeterlocation)
I did this: text = Mid(entryvalue, delimeterlocation, Len(entryvalue) - delimeterlocation + 1)
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'm trying to extract my parameters from my SQL query to build my xml for an SSRS report. I want to be able to copy/paste my SQL into Excel, look through the code and find all instances of '#' and the appropriate parameter attached to it. These paramaters will ultimately be copied and pasted to another sheet for further use. So for example:
where DateField between #FromDate and #ToDate
and (BalanceFiled between #BalanceFrom and #BalanceTo
OR BalancdField = #BalanceFrom)
I know I can use Instr to find the starting position of the first '#' in a line but how then do I go about extracting the rest of the parameter name (which varies) and also, in the first two lines of the example, finding the second parameter and extracting it's variable lenght? I've also tried using the .Find method which I've been able to copy the whole line over but not just the parameters.
I might approach this problem like so:
Remove characters that are not surrounded by spaces, but do not
belong. In your example, the parentheses need to be removed.
Split the text using the space as a delimiter.
For each element in the split array, check the first character.
If it is "#", then the parameter is found, and it is the entire value in that part of the array.
My user-defined function looks something like this:
Public Function GetParameters(ByRef rsSQL As String) As String
Dim sWords() As String
Dim s As Variant
Dim sResult As String
'remove parentheses and split at space
sWords = Split(Replace(Replace(rsSQL, ")", ""), "(", ""), " ")
'find parameters
For Each s In sWords
If Left$(s, 1) = "#" Then
sResult = sResult & s & ", "
End If
Next s
'remove extra comma from list
If sResult <> "" Then
sResult = Left$(sResult, Len(sResult) - 2)
End If
GetParameters = sResult
End Function
I have a spreadsheet where the Item description is a variable length but always finishes with a "hard return" to force a wrapped line in the cell. I need to copy the first line of the cell into another cell.
Can I use INSTR to find the first instance of a hard return (invisible character) and then copy the first N-1 characters?
For example:
Dell PowerEdge R720XD
Chassis (Max of ......
OR
Dell OptiPlex 7010 Minitower
Intel Core.............
In all cases I need to copy the first line of the text in the cell, irrespective of length.
Any ideas how I could do this??
Yes, you can easily do this
strShort = Left(strLong, InStr(strLong, vbCrLf) - 1)
Some times (eep. when sourced from a Unix system), you might have to replace vbCrLf (carriage Return, LineFeed) with a vbLf only.
If you are not sure if it contains an Enter, this code will do
strShort = IIf(InStr(strLong, vbCrLf), Left(strLong, InStr(strLong, vbCrLf) - 2), strLong)
Depending on the type of line break you can do it this way:
InStr(Range("A1").Text, vbLf)
InStr(Range("A1").Text, vbCr)
InStr(Range("A1").Text, vbCrLf)
to get the text before the line break:
Left(Range("A1").Text, InStr(Range("A1").Text, vbLf) - 1)
to get the text after the line break:
Right(Range("A1").Text, InStr(Range("A1").Text, vbLf))
I was not able to add a comment to Ripster's code below. I needed a reputation of 50; mine's only 36, but that's really where this comment should go instead of a separate answer.
It seems to me that the last bit of Ripster's code,
Right(Range("A1").Text, InStr(Range("A1").Text, vbLf))
should be,
Right(Range("A1").Text, (Len(Range("A1")-InStr(Range("A1").Text, vbLf)) - 1)
And finally to regenerate the string without the break
strString = Left(Range("A1").Text, InStr(Range("A1").Text, vbLf) - 1) & Right(Range("A1").Text, (Len(Range("A1")-InStr(Range("A1").Text, vbLf)) - 1)
A note to the moderators : Please review this. I still consider mysefl as a beginner to VBA and my logic could be wrong.
my solution is:
strString = Replace(strString, vbLf, "")
It is useful even if the string contains more than one line brakes.