I have a long MySQL query in VBA.
I tried to put a space and '_'. What am I missing?
Sql = "insert IGNORE into nhc (date,dealer_code,name,area_executive,address1,address2,address3,area_territory_id,area_territory_name,micro_market_id,micro_market_name,town,postcode,state,area_name,distributor,remark,may_2020_ga,may_2020_awtu10,may_2020_sellin,may_2020_awmi10,jun_2020_ga,jun_2020_awtu10, _
jun_2020_sellin,jun_2020_awmi10,jul_2020_ga,jul_2020_awtu10,jul_2020_sellin,jul_2020_awmi10,aug_2020_ga,aug_2020_awtu10,aug_2020_sellin,aug_2020_awmi10,dealer_class,may_2020_projected_dealer_class,jun_2020_projected_dealer_class,jul_2020_projected_dealer_class,aug_2020_projected_dealer_class, _
current_clas_awtu_target,current_class_sellin_target,current_class_awmi_target,dealer_status,disc_date,ambitious_dealer?_y/n,shopfront_signage,may_2020_mnp_awtu10,jun_2020_mnp_awtu10,jul_2020_mnp_awtu10,aug_2020_mnp_awtu10,may_2020_ereload_sellin,jun_2020_ereload_sellin,jul_2020_ereload_sellin,aug_2020_ereload_sellin,may_2020_hero_sell_through,jun_2020_hero_sell_through,jul_2020_hero_sell_through,aug_2020_hero_sell_through _
,may_2020_ga_with_ocr,jun_2020_ga_with_ocr,jul_2020_ga_with_ocr,aug_2020_ga_with_ocr)values _
('" & row.Cells(1).Value & "', '" & row.Cells(2).Value & "','" & row.Cells(3).Value & "', '" & row.Cells(4).Value & "', '" & row.Cells(5).Value & "','" & row.Cells(6).Value & "', '" & row.Cells(7).Value & "', '" & row.Cells(8).Value & "','" & row.Cells(9).Value & "', '" & row.Cells(10).Value & "', '" & row.Cells(11).Value & "','" & _
row.Cells(12).Value & "', '" & row.Cells(13).Value & "', '" & row.Cells(14).Value & "','" & row.Cells(15).Value & "', '" & row.Cells(16).Value & "', '" & row.Cells(17).Value & "','" & row.Cells(18).Value & "', '" & row.Cells(19).Value & "', '" & row.Cells(20).Value & "','" & row.Cells(21).Value & "', '" & row.Cells(22).Value & "', '" & row.Cells(23).Value & "','" & row.Cells(24).Value & "', '" & row.Cells(25).Value & "', '" & _
row.Cells(26).Value & "','" & row.Cells(27).Value & "', '" & row.Cells(28).Value & "', '" & row.Cells(29).Value & "','" & row.Cells(30.Value & "', '" & _
row.Cells(31).Value & "', '" & row.Cells(32).Value & "','" & row.Cells(33).Value & "', '" & row.Cells(34).Value & "', '" & row.Cells(35).Value & "','" & row.Cells(36).Value & "', '" & row.Cells(37).Value & "', '" & row.Cells(38).Value & "','" & _
row.Cells(39).Value & "', '" & row.Cells(40).Value & "', '" & row.Cells(41).Value & "','" & row.Cells(42).Value & "', '" & row.Cells(43).Value & "', '" & row.Cells(44).Value & "','" & row.Cells(45).Value & "', '" & row.Cells(46).Value & "', '" & row.Cells(47).Value & "','" & row.Cells(48).Value & "', '" & row.Cells(49).Value & "', '" & row.Cells(50).Value & "','" & row.Cells(51).Value & "', '" & row.Cells(52).Value & "', '" & row.Cells(53).Value & "','" & row.Cells(54).Value & "', '" & row.Cells(55).Value & "', '" & _
row.Cells(56).Value & "','" & row.Cells(57).Value & "', '" & row.Cells(58).Value & "', '" & row.Cells(59).Value & "','" & row.Cells(60).Value & "', '" & row.Cells(61).Value & "')"
Break it into pieces:
SQL = "insert IGNORE into nhc"
SQL = SQL & " (date,dealer_code,name,area_executive,"
etc...
and pay attention to spaces in the right place. I like to make sure each line starts with a space (as shown above) so it's easy to tell if you are missing one.
Max String Size in VBA
Also consider using parameters instead for something like this so you dont need a string that is a million miles long.
There are no string literals in the VBA. You need to end each line by closing off the quotes, an ampersand to concatenate the next line and an underscore as a line continuation " & _.
Using WorksheetFunction.TextJoin() will make your life a lot easier.
Sql = "insert IGNORE into nhc (date" & _
"dealer_code, name, area_executive, address1, address2, address3, " & _
"area_territory_id, area_territory_name, micro_market_id, micro_market_name, town, postcode, " & _
"state, area_name, distributor, remark, may_2020_ga, may_2020_awtu10, " & _
"may_2020_sellin, may_2020_awmi10, jun_2020_ga, jun_2020_awtu10, jun_2020_sellin, jun_2020_awmi10, " & _
"jul_2020_ga, jul_2020_awtu10, jul_2020_sellin, jul_2020_awmi10, aug_2020_ga, aug_2020_awtu10, " & _
"aug_2020_sellin, aug_2020_awmi10, dealer_class , may_2020_projected_dealer_class, jun_2020_projected_dealer_class, jul_2020_projected_dealer_class, " & _
"aug_2020_projected_dealer_class, current_clas_awtu_target, current_class_sellin_target, current_class_awmi_target, dealer_status, disc_date, " & _
"ambitious_dealer?_y/n, shopfront_signage, may_2020_mnp_awtu10, jun_2020_mnp_awtu10, jul_2020_mnp_awtu10, aug_2020_mnp_awtu10, " & _
"may_2020_ereload_sellin, jun_2020_ereload_sellin, jul_2020_ereload_sellin, aug_2020_ereload_sellin, may_2020_hero_sell_through, jun_2020_hero_sell_through, " & _
"jul_2020_hero_sell_through, aug_2020_hero_sell_through, may_2020_ga_with_ocr, jun_2020_ga_with_ocr, jul_2020_ga_with_ocr, aug_2020_ga_with_ocr, " & _
"Error 2042) VALUES" & _
"('" & WorksheetFunction.TextJoin("', '", False, Row.Resize(1, 60)) & ")"
I'm not sure if there is any documentation to support my answer specifically but per the Microsoft Documentation for the String Data Type:
You must enclose a String literal within quotation marks (" ").
Your continuations weren't working because they were within your string until you start adding the row.Cells(x).Value bits.
For the continuaton to be correct, per MS documentation for Visual Basic How To: Break and Combine Statements:
Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return) or (starting with version 16.0) a comment followed by a carriage return.
Note: This documentation is for Visual Basic. To make it relevant to Visual Basic for Applications you must concatenate (&) the string with the line-continuation character if you are continuing the string literal onto a new line; e.g:
"This string will be continued" & _
" on this line."
To use the line continuation correctly with your provided string, it should look like this:
Sql = "insert IGNORE into nhc (date,dealer_code,name,area_executive,address1,address2,address3,area_territory_id,area_territory_name,micro_market_id,micro_market_name,town,postcode,state,area_name,distributor,remark,may_2020_ga,may_2020_awtu10,may_2020_sellin,may_2020_awmi10,jun_2020_ga,jun_2020_awtu10," & _
" jun_2020_sellin,jun_2020_awmi10,jul_2020_ga,jul_2020_awtu10,jul_2020_sellin,jul_2020_awmi10,aug_2020_ga,aug_2020_awtu10,aug_2020_sellin,aug_2020_awmi10,dealer_class,may_2020_projected_dealer_class,jun_2020_projected_dealer_class,jul_2020_projected_dealer_class,aug_2020_projected_dealer_class," & _
" current_clas_awtu_target,current_class_sellin_target,current_class_awmi_target,dealer_status,disc_date,ambitious_dealer?_y/n,shopfront_signage,may_2020_mnp_awtu10,jun_2020_mnp_awtu10,jul_2020_mnp_awtu10,aug_2020_mnp_awtu10,may_2020_ereload_sellin,jun_2020_ereload_sellin,jul_2020_ereload_sellin,aug_2020_ereload_sellin,may_2020_hero_sell_through,jun_2020_hero_sell_through,jul_2020_hero_sell_through,aug_2020_hero_sell_through" & _
" ,may_2020_ga_with_ocr,jun_2020_ga_with_ocr,jul_2020_ga_with_ocr,aug_2020_ga_with_ocr)values" & _
" ('" & row.Cells(1).Value & "', '" & row.Cells(2).Value & "','" & row.Cells(3).Value & "', '" & row.Cells(4).Value & "', '" & row.Cells(5).Value & "','" & row.Cells(6).Value & "', '" & row.Cells(7).Value & "', '" & row.Cells(8).Value & "','" & row.Cells(9).Value & "', '" & row.Cells(10).Value & "', '" & row.Cells(11).Value & "','" & _
row.Cells(12).Value & "', '" & row.Cells(13).Value & "', '" & row.Cells(14).Value & "','" & row.Cells(15).Value & "', '" & row.Cells(16).Value & "', '" & row.Cells(17).Value & "','" & row.Cells(18).Value & "', '" & row.Cells(19).Value & "', '" & row.Cells(20).Value & "','" & row.Cells(21).Value & "', '" & row.Cells(22).Value & "', '" & row.Cells(23).Value & "','" & row.Cells(24).Value & "', '" & row.Cells(25).Value & "', '" & _
row.Cells(26).Value & "','" & row.Cells(27).Value & "', '" & row.Cells(28).Value & "', '" & row.Cells(29).Value & "','" & row.Cells(30.Value & "', '" & _
row.Cells(31).Value & "', '" & row.Cells(32).Value & "','" & row.Cells(33).Value & "', '" & row.Cells(34).Value & "', '" & row.Cells(35).Value & "','" & row.Cells(36).Value & "', '" & row.Cells(37).Value & "', '" & row.Cells(38).Value & "','" & _
row.Cells(39).Value & "', '" & row.Cells(40).Value & "', '" & row.Cells(41).Value & "','" & row.Cells(42).Value & "', '" & row.Cells(43).Value & "', '" & row.Cells(44).Value & "','" & row.Cells(45).Value & "', '" & row.Cells(46).Value & "', '" & row.Cells(47).Value & "','" & row.Cells(48).Value & "', '" & row.Cells(49).Value & "', '" & row.Cells(50).Value & "','" & row.Cells(51).Value & "', '" & row.Cells(52).Value & "', '" & row.Cells(53).Value & "','" & row.Cells(54).Value & "', '" & row.Cells(55).Value & "', '" & _
row.Cells(56).Value & "','" & row.Cells(57).Value & "', '" & row.Cells(58).Value & "', '" & row.Cells(59).Value & "','" & row.Cells(60).Value & "', '" & row.Cells(61).Value & "')"
You'll notice that now each line is enclosed in quotation marks, followed by a space and underscore. With the formatting on SO, the underscore is now white in colour showing it's not part of the string literal anymore (which is red) as it's not enclosed in the quotation marks any longer.
With saying all that, I'd agree with the answer from Brax that it'd be 'better' to break your string down into smaller pieces and concatenate the smaller chunks together and the use of parameters to help reduce string size.
Related
I would like to use in my query the key like this: '"prod.cd_produit"'||'"/"'||'" & strQ & "'.
Here, the values of my variables are: prod.cd_produit= 53 and & strQ & =350, so I would like to have 53/350 as a key.
I'm wondering if it's right to write '"prod.cd_produit"'||'"/"'||'" & strQ & "' (I don't want to have any spaces neither at right nor at left). This is a part of my code :
Public Sub INFO_PROTO34(ByRef strQ As String)
...........................................
" sousc.lp_etat_doss not in ('ANNUL','A30','IMPAY') and sousc.is_produit = prod.is_produit" & _
" and '"prod.cd_produit"'||'"/"'||'" & strQ & "' = proto.cd_protocole ",
Thank you very much for your help!
Like this:
RECSET.Open " select proto.b_perf_cma as b_perf_cma from db_dossier sousc,db_produit prod, " & _
" db_protocole proto where sousc.no_police = '" & numero_de_police & "' " & _
" and sousc.cd_dossier = 'SOUSC' " & _
" and sousc.lp_etat_doss not in ('ANNUL','A30','IMPAY') " & _
" and sousc.is_produit = prod.is_produit " & _
" and prod.cd_produit||'/'||'" & strQ & "' = proto.cd_protocole ", _
cnn_Pegase, adOpenDynamic, adLockBatchOptimistic
helps to spend some time formatting your SQL so it's more readable (for us and you...)
i'm trying to update an already open macro file (.xlsm) using update Query. the Update Query updates the the macro sheet sometimes but misses to update the sheet in some cases where there is no error appearing in this case.
My connection strig:
connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbpath & ";Extended Properties=""Excel 12.0 Macro;HDR=YES"";"
Update Query:
strSQL = "UPDATE [" & QuerySheet & "] SET [Alias]= '" & Alias &
"',[Tolerable Error]= '" & TE & "', [Account Type]= '" &
AccountTypeList & "',[Account Sub-Type]= '" & AccountSubTypeList &
"',[Account Class]= '" & AccountClassCheckbox & "' ,[Account
Sub-Class]= '" & AccountSubClassCheckbox & "',[GL Accounts]= '" &
GLAccountsCheckbox & "',[Scoping Dropdown Selection]= '" &
ComboBoxSelectedValue & "',[Account Type (ALL)]='" & AccountTypeList &
"',[Account Sub-type (ALL)]='" & AccountSubTypeList & "',[Account
Class (ALL)]='" & AccountClassList & "',[Account Sub-class (ALL)]='" &
AccountSubClassList & "',[GL Accounts (ALL)]='" & GLAccountList & "'
Where [Category Name]= '" & PrimaryStatement & "' AND [Group]='" &
GroupCounter & "'"
strSQL = "UPDATE [" & QuerySheet & "] SET [Alias]= '" & Alias & "',[Tolerable Error]= '" & TE & "', [Account Type]= '" & AccountTypeList & "',[Account Sub-Type]= '" & AccountSubTypeList & "',[Account Class]= '" & AccountClassCheckbox & "' ,[Account Sub-Class]= '" & AccountSubClassCheckbox & "',[GL Accounts]= '" & GLAccountsCheckbox & "',[Scoping Dropdown Selection]= '" & ComboBoxSelectedValue & "',[Account Type (ALL)]='" & AccountTypeList & "',[Account Sub-type (ALL)]='" & AccountSubTypeList & "',[Account Class (ALL)]='" & AccountClassList & "',[Account Sub-class (ALL)]='" & AccountSubClassList & "',[GL Accounts (ALL)]='" & GLAccountList & "' Where [Category Name]= '" & PrimaryStatement & "' AND [Group]='" & GroupCounter & "'"
I am getting application-defined error 1004 for the formula where I am trying to find the cells with only public email ids such as gmail yahoo etc. I replaced # with # previously.
Dim n As String
n = vbNullString
ActiveCell.Formula = "=IF(LEN(G2)-LEN(SUBSTITUTE(G2," & "#" & "," & n & "))=LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(G2," & "#gmail.com" & "," & "^" & ")," & "#yahoo.com" & "," & "^" & ")," & "#yahoo.co.in" & "," & "^" & ")," & "#rediffmail.com" & "," & "^" & ")," & "#hotmail.com" & "," & "^" & "))-LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(G2," & "#gmail.com" & "," & "^" & ")," & "#yahoo.com" & "," & "^" & ")," & "#yahoo.co.in" & "," & "^" & ")," & "#rediffmail.com" & "," & "^" & ")," & "#hotmail.com" & "," & "^" & ")," & "^" & "," & "))," & "All Public recipients" & "," & "OK" & ")"
Newbie here.
I use Excel as a front end and Access as a back end to store data. I am trying to take a query and write the values to an Access table using VBA in Excel. I get an Either BOF or EOF is True error, and when I run the SQL statement in Access, I get records.
Any feedback would be very much appreciated. Thank you in advance.
Here is my code:
Sub Write_Timesheet_AJ()
'**********************************************JGT**********************************************
'Transpose Data for HCS
'2018.09.17
'**********************************************JGT**********************************************
strPath1 = "C:\Reports\Timesheets\"
strFile1 = "Timesheets.accdb"
strDB = strPath1 & strFile1
Conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strDB & "; Persist Security Info=False;"
Conn.Open strDB
Conn.CursorLocation = adUseClient
'Clear table
strSQL = "Delete * From tbl_Timesheet_AJ;"
Set rs2 = Conn.Execute(strSQL)
'Transpose Data
strSQL = "Select VisitDate As VisitDt, PatientName, vw_Days_Worked_AJ.CaregiverCode As CaregiverCode, CaregiverName as AideName, CoordinatorName As Coordinator, " _
& "Street_1 As Street1, Street_2 As Street2, City1 As City, State1 as State, Zip, [Language] as L1 " _
& "From vw_Days_Worked_AJ Left Join vw_Caregiver_Info_AJ On vw_Days_Worked_AJ.CaregiverCode = vw_Caregiver_Info_AJ.CaregiverCode;"
Set rs1 = Conn.Execute(strSQL)
If rs1.RecordCount = 0 Then 'Record count check
Debug.Print strSQL
Debug.Print rs1.BOF
Debug.Print rs1.EOF
rs1.Close
Set rs1 = Nothing
Conn.Close
' MsgBox "There are no records; please check data."
Else
rs1.MoveFirst
rsCount1 = rs1.RecordCount
ReDim arrData1(rsCount1)
For loopX = 1 To rsCount1
With arrData1(loopX)
.VisitDt = Format(rs1.Fields("VisitDt"), "m/dd")
.WkEndDt = Get_Fri_Dt(CDate(rs1.Fields("VisitDt")))
.DayOfWk = Left(Get_Day_of_Wk(CDate(rs1.Fields("VisitDt"))), 3)
.PatientName = rs1.Fields("PatientName")
.CaregiverCode = rs1.Fields("CaregiverCode")
.AideName = rs1.Fields("AideName")
.Coordinator = rs1.Fields("Coordinator")
If IsNull(rs1.Fields("Street1")) Then .Street1 = " " Else .Street1 = rs1.Fields("Street1")
If IsNull(rs1.Fields("Street2")) Then .Street2 = " " Else .Street2 = rs1.Fields("Street2")
If IsNull(rs1.Fields("City")) Then .City = " " Else .City = rs1.Fields("City")
If IsNull(rs1.Fields("State")) Then .State = " " Else .State = rs1.Fields("State")
If IsNull(rs1.Fields("Zip")) Then .Zip = " " Else .Zip = rs1.Fields("Zip")
If IsNull(rs1.Fields("L1")) Then .L1 = " " Else .L1 = rs1.Fields("L1")
strInsert = "Insert Into tbl_Timesheet_AJ " _
& "(WkEndDt, PatientName, CaregiverCode, AideName, Coordinator, " & .DayOfWk & ", " _
& "AideName2, CaregiverCode2, Street1, Street2, City, State, Zip, L1) " _
& "Values (#" & .WkEndDt & "#, '" & .PatientName & "', '" & .CaregiverCode & "', " _
& "'" & .AideName & "', '" & .Coordinator & "', '" & .VisitDt & "', '" & .AideName & "', " _
& "'" & .CaregiverCode & "', '" & .Street1 & "', '" & .Street2 & "', '" & .City & "', " _
& "'" & .State & "', '" & .Zip & "', '" & .L1 & "');"
Set rs2 = Conn.Execute(strInsert)
rs1.MoveNext
End With
Next loopX
rs1.Close
Set rs1 = Nothing
Conn.Close
End If
End Sub
Wondering if you could help. I am populating a table on Excel which has an undetermined length (it grows as people add to it). This indeterminable amount of data needs to be added to a database in Access through the use of a button in Excel. I have produced the following code to try to alleviate this but get a
Run-time error '3709': The connection cannot be used to perform this operation. It is either closed or invalid in this context.
When I open up debugging it points to this line:
rs.Open sqlstr, DBCont
This can be found in the code below:
Sub submittoDB()
Dim DBCont As Variant
Set DBCont = CreateObject("ADODB.connection")
Dim StrDBPath As String
StrDBPath = "PATH Here\Database1.accdb"
Dim sConn As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & StrDBPath & ";" & _
"Jet OLEDB:Engine Type=5;" & _
"Persist Security Info=False;"
DBCont.Open sConn
MsgBox "Open DB"
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
Dim sqlstr As String
Dim endlimit As Integer
Dim i As Integer
endlimit = Cells(Rows.Count, "H").End(xlUp).Row + 1
'need to loop each line and remove test
For i = 5 To endlimit
sqlstr = "INSERT INTO DigiFinTracker (ProjectNo, ProjectName, Client, Tool, SuggAct, PercSav,PreDigCost,SuggSave,PropSav) VALUES ('" & Cells(6, 4) & "', '" _
& Cells(5, 4) & "', '" & Cells(4, 4) & "', '" & Cells(i, 8) & "', '" & Cells(i, 9) & "', '" & Cells(i, 10) _
& "', '" & Cells(i, 11) & "', '" & Cells(i, 12) & "', '" & Cells(i, 13) & "')"
rs.Open sqlstr, DBCont
DBCont.Close
Next i
DBCont.Close
End Sub
Apologies if the answer is fairly simplistic or I'm missing something crucial, I can't seem to get my head around what's wrong and whether it is possible to loop this type of process.
Many thanks for the responses in advance!
In the loop you are closing the connection on each iteration - DBCont.Close. Thus it does not work on the second iteration.
Either remove the DBCont.Close from the loop (advised) or open it every time and remove the DBCont.Open sConn before the loop:
For i = 5 To endlimit
DBCont.Open sConn 'It would work better if you delete this line
sqlstr = "INSERT INTO DigiFinTracker (ProjectNo, ProjectName, Client, Tool, SuggAct, PercSav,PreDigCost,SuggSave,PropSav) VALUES ('" & Cells(6, 4) & "', '" _
& Cells(5, 4) & "', '" & Cells(4, 4) & "', '" & Cells(i, 8) & "', '" & Cells(i, 9) & "', '" & Cells(i, 10) _
& "', '" & Cells(i, 11) & "', '" & Cells(i, 12) & "', '" & Cells(i, 13) & "')"
rs.Open sqlstr, DBCont
DBCont.Close 'And delete this line as well
Next i
To see what is causing the Data Missmatch try this:
sqlstr = "INSERT INTO DigiFinTracker (ProjectNo, ProjectName, Client, Tool, SuggAct, PercSav,PreDigCost,SuggSave,PropSav) VALUES ('" & Cells(6, 4) & "', '" _
& Cells(5, 4) & "', '" & Cells(4, 4) & "', '" & Cells(i, 8) & "', '" & Cells(i, 9) & "', '" & Cells(i, 10) _
& "', '" & Cells(i, 11) & "', '" & Cells(i, 12) & "', '" & Cells(i, 13) & "')"
Debug.Print sqlstr
take a look at the immediate window (Ctrl+G to open);
copy the SQL statement from there;
paste it in Access and work until you do not get some result from the query;