How can I remove rows starting with ' in a variant? - vba

Following the answer to this question, I execute different queries stored in a .txt file using the following code:
Dim vSql As Variant
Dim vSqls As Variant
Dim strSql As String
Dim intF As Integer
intF = FreeFile()
Open "MyFile.txt" For Input As #intF
strSql = Input(LOF(intF), #intF)
Close intF
vSql = Split(strSql, ";")
On Error Resume Next
For Each vSqls In vSql
DoCmd.RunSQL vSqls
Next
The queries are separated by ;, and each query is preceded by a comment line, starting with ' and ending with ;(so that it gets split by vSql = Split(strSql, ";") ).
The resulting vSql variant is composed of valid SQL statements, interspersed with comment lines starting with '. The current code works, but I would like to remove the On Error Resume Next so that a faulty SQL statement returns an error instead of being ignored.
How can I remove the rows starting with ' in the variant before executing the For Each loop? Or is there another way to accomplish my goal? The comment character can be changed if necessary.

Alternatively, this should do it to:
For Each vSqls In vSql
If Not CStr(vSqls) Like "'*" Then DoCmd.RunSQL vSqls
Next

It depends on exactly how the file is stored, but the simplest way is to find the first return character and take the rest of the text.
vSqls=mid(vSqls = Mid(vSqls, InStr(vSqls, vbCrLf) + 2)
or
vSqls=mid(vSqls = Mid(vSqls, InStr(vSqls, vbCr) + 1)
Bear in mind that this will only remove the first line so if there are blanks you will need to check whether the next line starts with a '.
And you might find that your queries don't work if they are spread across more than one line that you might need to deal with that by replacing any remaining carriage returns with a space.

Related

Why do I get multiple results from a MAX SQL query?

In Access, I have a table named tblBundle and am trying to query the last step that was completed on every bundle in an order.
tblBundle contains: Work Order, Bundle #, BundleLtr, Step, Complete [boolean]
I ultimately want to copy this into vba to create a list of the Bundle #, Ltr, and last step completed for continued data entry on the next step completed.
For some reason I cannot ascertain, the SQL query below returns 2 records for bundle 1 (190, 200) when I believe it should only be returning one record - 200.
SELECT Max(tblBundle.Step) AS intLstep, tblBundle.BundleNbr, tblBundle.BundleLtr,
tblBundle.Complete
FROM tblBundle
GROUP BY tblBundle.WO, tblBundle.BundleNbr, tblBundle.BundleLtr, tblBundle.Complete
HAVING (((tblBundle.WO)="195687-1-1") AND ((tblBundle.Complete)=True));
Can anyone help me figure out why my query is returning the extra value?
In MsAccess, NULL values appear as blanks when viewed on the Datasheet view. Also, it seems that when blanks are entered for a ShortText column on the Datasheet view, they are turned into NULLs (on my version of MsAccess). It seems that your data may have NULL for one of the Steps (say 200), and spaces (zero or more) for the other (say Step 190), you could force your query to treat both the same way:
SELECT Max(tblBundle.Step) AS intLstep, tblBundle.BundleNbr,
nz(tblBundle.BundleLtr,'') as BundleLtr,
tblBundle.Complete
FROM tblBundle
GROUP BY tblBundle.WO, tblBundle.BundleNbr,
nz(tblBundle.BundleLtr,''), tblBundle.Complete
HAVING (((tblBundle.WO)="195687-1-1") AND ((tblBundle.Complete)=True));
Please note that the invisible character can, in fact, be a character that looks like space, but it is not (like non-breaking space), etc. If the above solution does not work, try something like:
SELECT asc(mid(BundleLtr, 1,1)), asc(mid(BundleLtr, 2,1)) FROM Table2 where Step=190
To see the ascii values of the data in that column.
It seems like because your query is breaking down the the result and also returning BundleNbr is causing it to take both Max because its valid.
Also you break this down in your Group By statement and aggregate by that.
Both values of 190 and 200 have a BundleNbr of 1. If you remove that column you'll get the actual max value of 200 (If you want the max of intLStep.
I was able to use this following function to "clean up" my string and remove the additional 'Bundle 1'. This does not solve the original question, but works for my purposes.
'[Removes duplicate values from a string]
Function DeDupeString(ByVal sInput As String, Optional ByVal sDelimiter As
String = ",") As String
Dim varSection As Variant
Dim sTemp As String
For Each varSection In Split(sInput, sDelimiter)
If InStr(1, sDelimiter & sTemp & sDelimiter, sDelimiter & varSection & sDelimiter, vbTextCompare) = 0 Then
sTemp = sTemp & sDelimiter & varSection
End If
Next varSection
DeDupeString = Mid(sTemp, Len(sDelimiter) + 1)
End Function
Found From: Removing Duplicate values from a string in VBA

Duplicate row in a table after insert

I have a block of code that imports data from a text file to a table in Access. Each row in the text file should be saved separately in the table, but sometimes I have a duplicate row in the table. For example I have a text file like this:
Water
Bird
Summer
Sometimes and NOT always I see two Summer in the table. Always the last row of the text file is duplicated.
here is my VB code:
Private Sub Command11_Click()
Dim ifile As Integer
Dim db As Database
Dim name As String
Let ifile = FreeFile
name = util1.fDateiName("*.lab", "Lable")
Me.RecordSource = ""
DoCmd.RunSQL ("DELETE * FROM tb_lable_Daten")
Me.RecordSource = "SELECT name FROM tb_lable_Daten"
If name <> "" Then
Open name For Input As ifile
While Not EOF(ifile)
Line Input #ifile, entireline
'MsgBox entireline
DoCmd.RunSQL ("INSERT INTO tb_lable_Daten (name) VALUES ('" & entireline & "');")
Wend
List5.Requery
List5.SetFocus
MsgBox ("Die Daten sind erfolgreich gespeichert")
End If
End Sub
How can I solve this problem? and why does this problem occur?
In my view it seems somehow the file is processing beyond the last
line (which is summer in this case). Since you are not initializing
the varaible i:e entireline during each iteration so for the messed up
case its taking the last valid input (summer in your case). Try to
check and insert if and only if you have a valid value in entireline
variable and then re-initialize the entireline variable to blank after insertion. I hope this will solve the issue.

Split text File into Access DB using SQL

All,
This is an example of three lines in my text File NEW_SCANNING.txt:
I;05/29/2013;06:55:37;3124480071200;1;801;1;;1
I;05/29/2013;06:56:05;0049004004827;1;801;1;;1
I;05/29/2013;06:56:09;54491069;1;801;1;;1
I want to be able to select what's between the 3rd and 4th " ; ", in this case it would be
3124480071200
0049004004827
54491069
So what I need the program to do is to search every line that starts with the letter I and select what's between the 3rd and 4th ;.
Then it has to put the first selection in a combobox named SelBarc. If it has done this for the first, it has to move on to the second and so on and so on ...
Anyone who can help me?
Open, read, split to lines then loop;
dim lines() as string,i as long
Open "c:\xxx\NEW_SCANNING.txt" for input as #1
lines = split(Input$(lof(1), #1), vbcrlf)
close #1
For i = 0 to ubound(lines)
if Left$(lines(i), 1) = "I" then combobox.additem split(lines(i), ";")(3)
Next

VBA to Trim all Cells in an Access Table

I'm relatively experienced with Object oriented programming, but this is my first time ever working in Office with VBA and I'm entirely stumped by the syntax. I've been doing some searching and messing with it for the past hour or so, but have been trouble actually getting a macro that runs successfully and does what I need.
I'm attempting to loop through every cell in an Access table and apply the Trim function to the contents of that cell and, as a bonus, I'd like to remove all extra spaces in the string (if any). I.e. " Trim this__string " would simply become "Trim this string" (I used the underscore there to represent individual, multiple spaces since StackOverflow didn't want to show my multiple spaces).
Any code example of doing something like this, or at least something to get me close and then I can tinker with it, would be greatly appreciated. Thanks!
You can remove leading and trailing spaces with the Trim() function in a query.
UPDATE YourTable
SET text_field = Trim(text_field);
If you will be doing this from within an Access session, you could use Replace() to replace a sequence of two spaces with a single space.
UPDATE YourTable
SET text_field = Replace(text_field, ' ', ' ');
However you may need to run that Replace() query more than once to get all the contiguous space characters down to only one.
You could also do a regular expression-based replacement with a user-defined function. I don't know if that's worth the effort, though. And a user-defined function is also only available from within an Access application session.
I overlooked the "every cell in a table" aspect. That makes this more challenging and I don't think you can solve it with a standard macro or query. You can however use VBA code to examine the TableDef, and iterate through its fields ... then call your Trim and/or Replace operations on any of those fields whose data type is text or memo.
Here's a rough code outline to identify which fields of a given table are text type.
Public Sub FindTextFields(ByVal WhichTable As String)
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Set db = CurrentDb
Set tdf = db.TableDefs(WhichTable)
For Each fld In tdf.Fields
If fld.Type = dbText Or fld.Type = dbMemo Then
Debug.Print "Do something with " & fld.Name
End If
Next
Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
End Sub
Option Compare Database
Private Sub Command3_Click()
Call findField(Text1.Value)
End Sub
Public Function findField(p_myFieldName)
Dim db As Database, _
tb As TableDef, _
fd As Field
'''''''''Clearing the contents of the table
DoCmd.RunSQL "delete * from Field_Match_Found"
Set db = CurrentDb
For Each tb In db.TableDefs
For Each fd In tb.Fields
If fd.Name = p_myFieldName Then
strsql = "INSERT INTO Field_Match_Found Values (""" & tb.Name & """, """ & fd.Name & """)"
DoCmd.RunSQL strsql
End If
Next fd
Next tb
Set fd = Nothing
Set tb = Nothing
Set db = Nothing
If DCount("Account_number", "Field_Match_Found") = 0 Then
MsgBox ("No match was found")
Else
MsgBox ("Check Table Field_Match_Found for your output")
''''''''''making textbox blank for next time
Text1.Value = ""
End Function

How do I delete all characters after the first space in a cell?

I have a list of city names followed by the state in which they are located all in one column in Excel. How can I delete everything after the first space so that the city name is the only thing that's left in the cell?
example: A1 = "johnson TX"
should be just A1= "johnson"
I assume you want a VBA solution since you tagged your question excel-vba.
This works:
Sub KeepCity()
Dim strCityAndState As String
Dim strCityOnly As String
strCityAndState = Range("A1").Value
strCityOnly = Left(strCityAndState, InStr(strCityAndState, " ") - 1)
Range("A2").Value = strCityOnly
End Sub
If you don't want VBA and want a cell formula instead, then #JToland's answer works fine, though this one is more concise and doesn't keep the trailing space character:
=LEFT(A1, FIND(" ",A1)-1)
Well doing something like this
=Mid(A1, 1, Find(" ",A1))
in another column should grab all text before the " ". So you could build another column with just all the city names and then you could use that column for your purposes.
If you are looking for a VBA function, you can use Left and InStr as shown below.
Dim Temp As String: Temp = "Hello_World! This is my first answer here. :D"
Temp = Left(Temp, InStr(Temp, " ")-1)
In which case, Temp will be "Hello_World!"
Use of Split function
An elegant approach is to use the first token of the Split function:
Code Example extracting from cell A1 to A2
Option Explicit
Sub KeepCity()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("MySheet") ' << Change to your sheet name
ws.[A2] = Split(ws.[A1], " ")(0)
End Sub
Alternative Syntax
Instead of cell abbreviations [A2] or [A1] you can also use:
ws.Range("A2").Value = Split(ws.Range("A1").Value, " ")(0)
Note
The resulting split 1-dimensional array is zero based, so you get the first part (or token) of the original string via index (0).
If you are looking for a second part, I recommend adding an additional delimiter value (" ") to the original string, e.g. s: MsgBox split(s & " "," ")(1). By that way you avoid error number 9 "Subscript out of range", if there is no delimiter in between at all, thus no second part at all.