Optimizing loop through Access Database - sql

I need help with an massive loop through a continously expanding Access database consisting of approximately 280.000 rows of data. The procedure adds 3000 rows of data every week, and the macros running time is therefore only increasing. It takes around one hour to complete.
What is the optimal way to complete my procedure? I'm experienced with VBA, but SQL knowledge is limited.
The issue summarized is that the If-statement, located in "Help needed here" runs through 280.000 rows of data for 3000 companies.
The goal is that the fresh weekly scores of the company will be scored in JQHistory, but it has to take the date of running the macro into consideration
Note: Everything outside of "Help needed here", I've optimized in another macro. I've left it to hopefully improve the context of the issue.
Here is the non-optimized macro:
Sub OpdaterKvant()
Dim wb As Workbook
Dim ws As Worksheet
Dim DatoIn As Date
Set db = New ADODB.Connection
Set DbEQ = New ADODB.Connection
'The location of the database is determined outside the macro'
strConn = ConnectionString
db.Open strConn
Set wb = Workbooks.Open("My File Location")
Set ws = wb.Worksheets(1)
n = ws.UsedRange.Rows.Count
DateIn = Right(ws.Cells(1, 1), 2) & "-" & Mid(ws.Cells(1, 1), 5, 2) & "-" & Left(ws.Cells(1, 1), 4)
Dato = Format(DateIn, "mm-dd-yyyy")
db.Execute ("DELETE * FROM JQScores")
For i = 3 To n
Sedol = Replace(ws.Cells(i, 1), " ", "")
Company = Left(Replace(ws.Cells(i, 2), "'", ""), Len(Replace(ws.Cells(i, 2), "'", "")) - 1)
Country = Replace(ws.Cells(i, 3), " ", "")
Region = Replace(ws.Cells(i, 4), " ", "")
Sector = Replace(ws.Cells(i, 5), " ", "")
MarketCap = Replace(Replace(ws.Cells(i, 6), " ", ""), ",", ".")
JQRank = Replace(ws.Cells(i, 7), " ", "")
ValueRank = Replace(ws.Cells(i, 8), " ", "")
QualityRank = Replace(ws.Cells(i, 9), " ", "")
MomentumRank = Replace(ws.Cells(i, 10), " ", "")
JQScore = Replace(Replace(ws.Cells(i, 11), " ", ""), ",", ".")
'Inserts the information into the Access database.'
Sql = "Insert into JQScores (Sedol, Company, Region, Sector, MarketCapUSD, JQ_Rank, Value_Rank, Quality_Rank, Momentum_Rank, JQ_Score, Country) VALUES ('" & Sedol & "','" & Company & "', '" & Region & "', '" & Sector & "', " & MarketCap & ", '" & JQRank & "', '" & ValueRank & "', '" & QualityRank & "', '" & MomentumRank & "', " & JQScore & ", '" & Country & "')"
db.Execute (Sql)
'*** HELP NEEDED IN THIS SECTION'
If db.Execute("Select Count(Id) as NumId from JQHistory where Sedol='" & Sedol & "' and history_date=#" & Dato & "#")("NumId") = 0 Then
Sql = "Insert into JQHistory (History_date, Sedol, Selskabsnavn, JQScore, JQ_Rank, Value_Rank, Momentum_Rank, Quality_Rank, Marketcap) VALUES (#" & Dato & "#, '" & Sedol & "','" & Company & "'," & JQScore & ", '" & JQRank & "', '" & ValueRank & "', '" & MomentumRank & "', '" & QualityRank & "', " & MarketCap & ")"
db.Execute (Sql)
Else
Sql = "Update JQHistory set MarketCap=" & MarketCap & ", Selskabsnavn='" & Company & "' , JQ_Rank='" & JQRank & "', Value_Rank='" & ValueRank & "', Quality_Rank='" & QualityRank & "', Momentum_Rank='" & MomentumRank & "', JQScore=" & JQScore & " WHERE SEDOL='" & Sedol & "' and History_Date=#" & Dato & "#"
db.Execute (Sql)
End If
'***'
Next i
db.Close
wb.Close

The optimal way ended up using the DAO.Recordset and DAO.Database options, and a lot of tweaks for optimization.
The biggest shortcut was using the 'Recordset.FindFirst' to identify if the data should only be added (takes 22 seconds), or update the data with identical date (takes 12 minutes). Although mainly the scenario taking 22 seconds will happen.
The scenario taking 12 minutes is not optimized since it rarely happens.
Full solution:
Sub OpdaterKvant()
Dim wb As Workbook
Dim wbOp As Workbook
Dim ws As Worksheet
Dim wsOp As Worksheet
Dim i, n As Integer
Dim db As DAO.Database
Dim rsScores As DAO.Recordset
Dim rsHistory As DAO.Recordset
StartTime = Timer
Call PERFORMANCEBOOST(False)
Set PB = CREATEPROGRESSBAR
With PB
.SetStepCount (4)
.Show
End With
Set wbOp = ThisWorkbook
Set wsOp = wbOp.ActiveSheet
'Step 1: Open JQGCLE
Set wb = Workbooks.Open("Location", ReadOnly:=True)
Set ws = wb.Worksheets(1)
ws.Activate
n = ws.UsedRange.Rows.Count
DateIn = Right(ws.Cells(1, 1), 2) & "-" & Mid(ws.Cells(1, 1), 5, 2) & "-" & Left(ws.Cells(1, 1), 4)
'Step 2: Optag værdier i Excel
PB.Update "Data hentes fra JQGLCE-ark"
ReDim Sedol(3 To n) As String
ReDim Company(3 To n) As String
ReDim Country(3 To n) As String
ReDim Region(3 To n) As String
ReDim Sector(3 To n) As String
ReDim MarketCap(3 To n) As String 'Tal
ReDim MarketCapSQL(3 To n) As String 'Tal
ReDim JQRank(3 To n) As String
ReDim ValueRank(3 To n) As String
ReDim QualityRank(3 To n) As String
ReDim MomentumRank(3 To n) As String
ReDim JQScore(3 To n) As String 'Tal
ReDim JQScoreSQL(3 To n) As String 'Tal
For i = 3 To n
Sedol(i) = Trim(ws.Cells(i, 1))
Company(i) = Left(Replace(ws.Cells(i, 2), "'", ""), Len(Replace(ws.Cells(i, 2), "'", "")) - 0) 'Stod tidligere på minus 1 - Hvorfor?
Country(i) = Trim(ws.Cells(i, 3))
Region(i) = Trim(ws.Cells(i, 4))
Sector(i) = Trim(ws.Cells(i, 5))
MarketCap(i) = ws.Cells(i, 6) 'Til DAO
MarketCapSQL(i) = Replace(ws.Cells(i, 6), ",", ".") 'Til SQL
JQRank(i) = Trim(ws.Cells(i, 7))
ValueRank(i) = Trim(ws.Cells(i, 8))
QualityRank(i) = Trim(ws.Cells(i, 9))
MomentumRank(i) = Trim(ws.Cells(i, 10))
JQScore(i) = ws.Cells(i, 11) 'Til DAO
JQScoreSQL(i) = Replace(ws.Cells(i, 11), ",", ".") 'Til SQL
'DAO og SQL bliver behandlet forskelligt ift. komma
Next i
'Step 3: Indsæt værdier i Access-database
Set acc = New Access.Application
Set db = acc.DBEngine.OpenDatabase("Location", 1, 0)
'Step 3.1: JQScores
PB.Update "JQScores indsættes i databasen"
Set rsScores = db.OpenRecordset(Name:="JQScores", Type:=RecordsetTypeEnum.dbOpenDynaset)
db.Execute "DELETE * FROM JQScores"
For i = 3 To n
With rsScores
.AddNew
!Sedol = Sedol(i)
!Company = Company(i)
!Region = Region(i)
!Sector = Sector(i)
!MarketCapUSD = MarketCap(i)
!JQ_Rank = JQRank(i)
!Value_Rank = ValueRank(i)
!Quality_Rank = QualityRank(i)
!Momentum_Rank = MomentumRank(i)
!JQ_Score = JQScore(i)
!Country = Country(i)
.Update
End With
Next i
rsScores.Close
Set rsScores = Nothing
'Step 3.2: JQHistory
Set rsHistory = db.OpenRecordset(Name:="JQHistory", Type:=RecordsetTypeEnum.dbOpenDynaset)
With rsHistory
If .RecordCount <> 0 Then
i = 3
.FindFirst "History_Date = '" & DateIn & "'"
If .NoMatch = True Then
'Hvis datoen ikke er i datasættet, bliver dataen tilføjet
PB.Update "Hurtig: JQHistory indsættes i databasen"
For i = 3 To n
.AddNew
!History_Date = DateIn
!Sedol = Sedol(i)
!Selskabsnavn = Company(i)
!MarketCap = MarketCap(i)
!JQ_Rank = JQRank(i)
!Value_Rank = ValueRank(i)
!Quality_Rank = QualityRank(i)
!Momentum_Rank = MomentumRank(i)
!JQScore = JQScore(i)
.Update
Next i
Else
'Hvis datoen allerede er der, skal den opdateres
PB.Update "Langsom: JQHistory indsættes i databasen"
For i = 3 To n
db.Execute ("UPDATE JQHistory SET MarketCap=" & MarketCapSQL(i) & ", Selskabsnavn='" & Company(i) & "', JQ_Rank='" & JQRank(i) & "', Value_Rank='" & ValueRank(i) & "', Quality_Rank='" & QualityRank(i) & "', Momentum_Rank='" & MomentumRank(i) & "', JQScore=" & JQScoreSQL(i) & " WHERE SEDOL='" & Sedol(i) & "' and History_Date='" & DateIn & "'")
Next i
End If
End If
End With
rsHistory.Close
Set rsHistory = Nothing
'Step 4: Færdiggørelse
acc.DoCmd.Quit acQuitSaveAll 'Lukker og gemmer database
Set db = Nothing
wsOp.Activate
wsOp.Range("B7").Value = "Seneste data benyttet: " & DateIn
wb.Close SaveChanges:=False
Call PERFORMANCEBOOST(True)
Unload PB
MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox "Opdatering fuldført. Proceduren tog " & MinutesElapsed & "."
End Sub

Related

find missing number buckets

I was wondering if there's a better way
I need to find missing number buckets. There's a set of number buckets in which the weights are distributed. I want to make sure that if the user misses a number somewhere, his attention is drawn to it and hes told that he's missing some buckets, otherwise his data for these will not show.
I already found each missing number but it shows a line for each and the user is only interested in the entire bucket.
so, I need the thing on the left to become the thing on the right. The FROM and TO is what I have to work with.
I have a feeling there's some beautiful VBA solution for this, something with arrays :)
Besides all this ugliness that I wrote, to get the original missing weight, I had to create a table with all weights from 0 to 1000. there has to be a better way
Sub sbMissingBuckets()
Dim vrQDF As Object
Dim vrSQL As String
Dim vrQueryName As String
Dim vrCountsMissingBuckets As Long
sbWOff
DoCmd.RunSQL "DELETE FROM MissingServicesShippingWeightBuckets"
Dim vrRs1 As DAO.Recordset
Dim vrServicesShippingWeightCollectionID As Long
Set vrRs1 = CurrentDb.OpenRecordset("SELECT ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID FROM ServicesShippingWeightBuckets GROUP BY ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID " & _
", ServicesShippingWeightBuckets.IsMultiweight HAVING (((ServicesShippingWeightBuckets.IsMultiweight)=False));")
Do Until vrRs1.EOF
vrServicesShippingWeightCollectionID = vrRs1("ServicesShippingWeightCollectionID")
vrSQL = "SELECT ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID, AllWeights.Weight FROM ServicesShippingWeightBuckets " & _
", AllWeights GROUP BY ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID, AllWeights.Weight, IIf([WeightFromInequalitySymbolID]=1,IIf([WeightToInequalitySymbolID]=3,[Weight]>[WeightFrom] " & _
"AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>[WeightFrom] AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>[WeightFrom] " & _
"AND [Weight]<=999999999)) & IIf([WeightFromInequalitySymbolID]=2,IIf([WeightToInequalitySymbolID]=3,[Weight]>=[WeightFrom] AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>=[WeightFrom] " & _
"AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>=[WeightFrom] AND [Weight]<=999999999)), ServicesShippingWeightBuckets.IsMultiweight " & _
"HAVING (((ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID)=" & vrServicesShippingWeightCollectionID & ") AND ((IIf([WeightFromInequalitySymbolID]=1,IIf([WeightToInequalitySymbolID]=3,[Weight]>[WeightFrom] " & _
"AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>[WeightFrom] AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>[WeightFrom] " & _
"AND [Weight]<=999999999)) & IIf([WeightFromInequalitySymbolID]=2,IIf([WeightToInequalitySymbolID]=3,[Weight]>=[WeightFrom] AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>=[WeightFrom] " & _
"AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>=[WeightFrom] AND [Weight]<=999999999)))=-1) " & _
"AND ((ServicesShippingWeightBuckets.IsMultiweight)=False)) ORDER BY AllWeights.Weight;"
vrQueryName = "qMissingBucketsBase"
fnDeleteObjectIfExists "Query", vrQueryName
Set vrQDF = CurrentDb.CreateQueryDef(vrQueryName, vrSQL)
'count qMissingBuckets
vrCountsMissingBuckets = dCount("cTo", "qMissingBuckets")
'if 0 do nothing
If vrCountsMissingBuckets > 0 Then
'loop thoruhg and onl add records to the table if the diff is more than 1
DoCmd.OpenQuery "qMissingBuckets2"
DoCmd.OpenQuery "qMissingBuckets3"
Dim vrRs2 As DAO.Recordset
Dim vrFrom As Long
Dim vrTo As Long
Dim vrDiff As Long
Dim vrPlaceholder As Boolean
Dim vrFromPlaceholder As Variant
Set vrRs2 = CurrentDb.OpenRecordset("mtT")
Do Until vrRs2.EOF
vrFrom = vrRs2("cFrom")
vrTo = vrRs2("cTo")
vrDiff = vrRs2("cDiff")
If vrDiff > 1 Then
If vrPlaceholder = False Then
If vrDiff < 99999 Then
DoCmd.RunSQL "INSERT INTO MissingServicesShippingWeightBuckets (ServicesShippingWeightCollectionID, ServicesShippingWeightBucket, WeightFromInequalitySymbolID, WeightFrom, WeightToInequalitySymbolID, WeightTo) SELECT " & vrServicesShippingWeightCollectionID & _
", '>=" & vrFrom & " and <" & vrTo & "', 2 as WeightFromInequalitySymbolID, " & vrFrom & " as WeightFrom, 3 as WeightToInequalitySymbolID, " & vrTo & " as WeightTo"
End If
Else
DoCmd.RunSQL "INSERT INTO MissingServicesShippingWeightBuckets (ServicesShippingWeightCollectionID, ServicesShippingWeightBucket, WeightFromInequalitySymbolID, WeightFrom, WeightToInequalitySymbolID, WeightTo) SELECT " & vrServicesShippingWeightCollectionID & _
", '>=" & vrFromPlaceholder & " and <" & vrTo & "', 2 as WeightFromInequalitySymbolID, " & vrFromPlaceholder & " as WeightFrom, 3 as WeightToInequalitySymbolID, " & vrTo & " as WeightTo"
vrPlaceholder = False
vrFromPlaceholder = Null
End If
ElseIf vrDiff = 1 Then
If vrPlaceholder = False Then
vrFromPlaceholder = vrFrom
vrPlaceholder = True
End If
End If
vrRs2.MoveNext
Loop
vrRs2.Close
Set vrRs2 = Nothing
End If
vrRs1.MoveNext
Loop
vrRs1.Close
Set vrRs1 = Nothing
sbWOn
End Sub

Slow running Loop. Looking to find way to execute multiple records per execute

I have an excel workbook that contains about 5,000 rows of data. I have two buttons mapped to macros. One button will delete all data in the table, and reinsert it from the Excel Workbook, and the other will only insert the 'new' rows based on a unique ID.
I am finding that both of these buttons are taking a long time to run. ~10-15 minutes. Right now, it is performing the insert for every row, but I am looking to combine this.
Basically, I would like to loop through ~100 or so rows then insert. Then loop through the next hundred rows and insert.
Any suggestions would be greatly appreciated. VBA / Coding in general is not my forte and i'm pulling a brick wall on this one.
Thanks!
Sub Rebuild_Click()
' ***********************
' ** Declare Variables **
' ***********************
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sSTATUS, sCHANNEL, sISSUE, sLOB, sDESC, sIN, sJN, sIS, sPRIME, sIU, sTR, sAU As String
Dim answer, sQTY, sRRSC, sOA, sMeetings, sOutages As Integer
Dim sDATE As Date
With Sheets("OASYS ADMIN TRACKER")
' ****************************
' ** Show Information Popup **
' ****************************
answer = MsgBox("You are about to update the database with ~5,000 records." & vbCrLf & "" & vbCrLf & "This will take approximately 5 minutes." & vbCrLf & "" & vbCrLf & "If you wish to continue, please press Yes. Otherwise, Press No" & vbCrLf & "" & vbCrLf & "----------" & vbCrLf & "EXCEL IS NOT FROZEN." & vbCrLf & "" & vbCrLf & "****DO NOT CLOSE EXCEL ****", vbYesNo + vbQuestion, "Update Database")
' ***********************
' ** Open IF Statement **
' ***********************
If answer = vbYes Then
' ***********************
' ** Connection String **
' ***********************
conn.Open "Provider=SQLNCLI11;Password=XXXXX;User ID=XXXXX;Initial Catalog=SupportAdmin;Data Source=tcp:XXXXX;"
' *************************
' ** Purge Existing Data **
' *************************
conn.Execute "Delete FROM dbo.TestDB"
' *********************
' ** Skip Leader Row **
' *********************
iRowNo = 4
' ************************
' ** Begin Dataset Loop **
' ************************
Do Until .Cells(iRowNo, 3) = ""
sID = .Cells(iRowNo, 1)
sSTATUS = .Cells(iRowNo, 2)
sDATE = .Cells(iRowNo, 3)
sCHANNEL = .Cells(iRowNo, 4)
sISSUE = .Cells(iRowNo, 5)
sQTY = .Cells(iRowNo, 6)
sLOB = .Cells(iRowNo, 7)
sDESC = .Cells(iRowNo, 8)
sIN = .Cells(iRowNo, 9)
sJN = .Cells(iRowNo, 10)
sIS = .Cells(iRowNo, 11)
sPRIME = .Cells(iRowNo, 12)
sIU = .Cells(iRowNo, 13)
sTR = .Cells(iRowNo, 14)
sAU = .Cells(iRowNo, 15)
sRRSC = .Cells(iRowNo, 16)
sOA = .Cells(iRowNo, 17)
sOutages = .Cells(iRowNo, 18)
sMeetings = .Cells(iRowNo, 19)
' ***********************
' ** Replace ' in Data **
' ***********************
sDESC = Replace(sDESC, "'", "''")
sIS = Replace(sIS, "'", "''")
sIU = Replace(sIU, "'", "''")
' *****************
' ** Execute SQL **
' *****************
conn.Execute "insert into dbo.TestDB (ID,STATUS,DATE,CHANNEL,ISSUE,QTY,LOB,[DESC],[IN],JN,[IS],PRIME,IU,TR,AU,RRSC,OA,OUTAGES,MEETINGS) " & _
"values ('" & sID & "','" & sSTATUS & "', '" & sDATE & "','" & sCHANNEL & "', '" & sISSUE & "', '" & sQTY & "', '" & sLOB & "', '" & sDESC & "', '" & sIN & "', '" & sJN & "', '" & sIS & "', '" & sPRIME & "', '" & sIU & "', '" & sTR & "', '" & sAU & "', '" & sRRSC & "', '" & sOA & "', '" & sOutages & "', '" & sMeetings & "')"
iRowNo = iRowNo + 1
Loop
' ****************************
' ** Show Information Popup **
' ****************************
MsgBox "Database Update Complete!"
' *****************************
' ** Close Connection String **
' *****************************
conn.Close
Set conn = Nothing
' ****************************
' ** Close IF Statement **
' ****************************
Else
' do nothing
End If
End With
End Sub
Tried your code with makeshift table in local SQL Server 2005 and found taking only 10 seconds for around 5000 records. In your case the delay may be due to Database Size, network speed etc.
However after trying it with code to insert 100 records at a time the same time reduced to 1 odd second only.
Sub test2()
Dim conn As New ADODB.Connection
Dim LastRow As Long, LastCol As Long, iRowNo As Long, DataArr As Variant
Dim SqStr As String, ValStr As String, Rw As Long, Cl As Long
Dim Ws As Worksheet, tm As Double
tm = Timer
conn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;;Initial Catalog=test;Data Source=USER-PC\SQLEXPRESS"
conn.Execute "Delete FROM dbo.Test"
Set Ws = ThisWorkbook.Worksheets("Sheet1")
iRowNo = 4
LastRow = Ws.Range("C" & Rows.Count).End(xlUp).Row
DataArr = Ws.Range("A" & iRowNo & ":S" & LastRow)
LastCol = UBound(DataArr, 2)
SqStr = "insert into dbo.Test (ID,STATUS,DATE,CHANNEL,ISSUE,QTY,LOB,[DESC],[IN],JN,[IS],PRIME,IU,TR,AU,RRSC,OA,OUTAGES,MEETINGS) "
'Sqlstr=Sqlstr & " Values " 'May use for Sql Server 2008 and above
For Rw = 1 To UBound(DataArr, 1)
DataArr(Rw, 1) = Replace(DataArr(Rw, 1), "'", "''")
DataArr(Rw, 8) = Replace(DataArr(Rw, 8), "'", "''")
DataArr(Rw, 13) = Replace(DataArr(Rw, 13), "'", "''")
'ValStr = ValStr & "('" 'May use for Sql Server 2008 and above
ValStr = ValStr & "Select '"
For Cl = 1 To UBound(DataArr, 2)
'ValStr = ValStr & DataArr(Rw, Cl) & IIf(Cl < LastCol, "','", "')") 'May use for Sql Server 2008 and above
ValStr = ValStr & DataArr(Rw, Cl) & IIf(Cl < LastCol, "','", "'") ' Used for test in Sql Server 2005
Next Cl
If Rw Mod 100 = 0 Then ' exceute at 100 records
ValStr = SqStr & ValStr
conn.Execute ValStr
DoEvents
ValStr = ""
Debug.Print Rw, Timer - tm
Else
If Rw < UBound(DataArr, 1) Then
'ValStr = ValStr & ", " 'Modify Comma / Space between datasets of two rows according Sql version Syntax
ValStr = ValStr & " UNION ALL " 'Used for test with Sql Server 2005.
End If
End If
Next Rw
If Rw Mod 100 > 0 Then
ValStr = SqStr & ValStr
conn.Execute ValStr
DoEvents
ValStr = ""
Debug.Print Rw, Timer - tm
End If
Debug.Print "Total Seconds Taken: " & Timer - tm
End Sub
The INSERT SQl syntax along with connection string etc may please be modified for the type & version used by you along with suggestion in #Raymond Nijland's comment.

MS Access 2010 VBA Integer Variable not changing in Loop

I have code that is looping through an array of member numbers and retrieving records for each. Each time, I need to use the count of the records returned up to 12. However, once the variable that is to hold the count is set, it will not reset with the next call. It also "jumps" from the first to the last record rather than looping through each. In other words, if there are 4 records returned by the recordset, it will execute for the first and the last and then give an error of "No Current Record" Here is my code:
Dim x As Integer
For i = 1 To intMembers
strGetMemberInfo = "SELECT PatientRecords.[Medication Name], PatientRecords.[First Name], PatientRecords.[Last Name],PatientRecords.[doc phone]" _
& " FROM PatientRecords WHERE member_no ='" & arrMembers(i) & "'"
Set rstMedicine = dbs.OpenRecordset(strGetMemberInfo, dbOpenSnapshot)
Dim intMedicine As Integer
intMedicine = rstMedicine.RecordCount
If intMedicine > 12 Then
intMedicine = 12
End If
Do Until rstMedicine.EOF
For x = 1 To intMedicine
strMedicationField = strMedication & x
strDoctorFNameField = strDoctorFName & x
strDoctorLNameField = strDocotrLName & x
strDoctorPhoneField = strDoctorPhone & x
strSQL = "UPDATE TransformationTable SET " & strMedicationField & " = '" & rstMedicine.Fields("[Medication Name]").Value & "'," & strDoctorFNameField & " = '" & rstMedicine.Fields("[First Name]").Value & "', " & strDoctorLNameField & " = '" & Replace(rstMedicine.Fields("[Last Name]"), "'", "''") & "', " & strDoctorPhoneField & " = '" & rstMedicine.Fields("[doc phone]").Value & "' WHERE member_no ='" & arrMembers(i) & "'"
dbs.Execute strSQL
rstMedicine.MoveNext
Next x
Loop
rstMedicine.Close
Set rstMedicine = Nothing
Next i
In the above code, intMedicinegets set by the first recordset and NEVER changes even though rstMedicine.RecordCount does change.
Any help is appreciated
You have 2 different issues. First, use rstMedicine.MoveLast to move to the bottom of the recordset and get the full count. Second. Your limiting the number of "cycles" to 12, but you are not exiting the loop after intMedicine is 12, so it is still trying to get to the end of the recordset because your code says "Do Until rstMedicine.EOF". Change your code to this:
Dim x As Integer
For i = 1 To intMembers
strGetMemberInfo = "SELECT PatientRecords.[Medication Name], PatientRecords.[First Name], PatientRecords.[Last Name],PatientRecords.[doc phone]" _
& " FROM PatientRecords WHERE member_no ='" & arrMembers(i) & "'"
Set rstMedicine = dbs.OpenRecordset(strGetMemberInfo, dbOpenSnapshot)
rstMedicine.MoveLast
Dim intMedicine As Integer
intMedicine = rstMedicine.RecordCount
If intMedicine > 12 Then
intMedicine = 12
End If
rstMedicine.MoveFirst
Do Until rstMedicine.EOF
For x = 1 To intMedicine
strMedicationField = strMedication & x
strDoctorFNameField = strDoctorFName & x
strDoctorLNameField = strDocotrLName & x
strDoctorPhoneField = strDoctorPhone & x
strSQL = "UPDATE TransformationTable SET " & strMedicationField & " = '" & rstMedicine.Fields("[Medication Name]").Value & "'," & strDoctorFNameField & " = '" & rstMedicine.Fields("[First Name]").Value & "', " & strDoctorLNameField & " = '" & Replace(rstMedicine.Fields("[Last Name]"), "'", "''") & "', " & strDoctorPhoneField & " = '" & rstMedicine.Fields("[doc phone]").Value & "' WHERE member_no ='" & arrMembers(i) & "'"
dbs.Execute strSQL
rstMedicine.MoveNext
If x = 12 Then
Exit Do
End If
Next x
Loop
rstMedicine.Close
Set rstMedicine = Nothing
Next i

Quotations in Access String from Excel VBA

Ok I am having a Problem using VBA from Excel 2010 to Query data in access, the problem comes when the variable Descripcheck, or Grouplocal, some of the descriptions have a "" in the excel cell so when it pulls the string itself this causes the query function gets a syntax error. Any ideas?
PMnum = Cells(B, 3)
Grouplocal = Cells(B, 4)
Descripcheck = Cells(B, 6)
DevTyp = Cells(B, 5)
TagName = Cells(B, 2)
If PMnum = "" Then
PMnum = " IS NULL"
Else:
PMnum = "=" & PMnum
End If
If Grouplocal = "" Then
Grouplocal = " IS NULL"
Else:
Grouplocal = "=" & Chr$(34) & Grouplocal & Chr$(34)
End If
If Descripcheck = "" Then
Descripcheck = " IS NULL"
Else:
Descripcheck = "=" & Chr$(34) & Descripcheck & Chr$(34)
End If
If DevTyp = "" Then
DevTyp = " IS NULL"
Else:
DevTyp = "=" & Chr$(34) & DevTyp & Chr$(34)
End If
If TagName = "" Then
TagName = " IS NULL"
Else:
TagName = "=" & Chr$(34) & TagName & Chr$(34)
End If
sCmndString = "SELECT Site_Data.Pass_Fail, Site_Data.Tag_Name, Site_Data.[PM_#],Site_Data.Group_Location_Reference, Site_Data.Device_Type, Site_Data.Description, Site_Data.Set_Point, Site_Data.Set_Point_Units, Site_Data.Fail_Low, Site_Data.Fail_High, Site_Data.As_Found, Site_Data.As_Left, Site_Data.Manufacturer_SN, Site_Data.Year_Put_Into_Service, Site_Data.Date_of_Test, Site_Data.Time_To_Complete, Site_Data.Service, Site_Data.Comments, Site_Data.Site, Site_Data.Year, Site_Data.Month " & _
"FROM Site_Data WHERE (((Site_Data.[PM_#])" & PMnum & ") AND " & _
"((Site_Data.Group_Location_Reference)" & Grouplocal & ") AND " & _
"((Site_Data.Device_Type)" & DevTyp & ") AND " & _
"((Site_Data.Description)" & Descripcheck & ") AND " & _
"((Site_Data.Site)=" & Chr$(34) & SiteName & Chr$(34) & ") AND " & _
"((Site_Data.Year)=" & Chr$(34) & yrs & Chr$(34) & ") AND " & _
"((Site_Data.Month)=" & Chr$(34) & Mnth & Chr$(34) & ") AND " & _
"((Site_Data.Tag_Name)" & TagName & "));"
Set rs = New ADODB.Recordset
rs.Open sCmndString, cnt, 2, 3, 1
If you keep fooling around with those "s and Chr$(34)s you'll drive yourself crazy. Try using a parameterized query instead. Consider the following (simplified) example. It uses some test data in Access...
Site_ID Device_Type Description
------- ----------- ------------
1 Type1 test1
2 Type1
3 Type1
4 Type2 "some" value
5 Type2 "some" value
6 Type2
7 Type2
8 Type2
...an Excel sheet that looks like this...
...and the code behind the button is
Option Explicit
Public Sub AccessLookup()
Dim con As ADODB.Connection, cmd As ADODB.Command, rst As ADODB.Recordset
Dim DevTyp As Variant, Descripcheck As Variant
Dim s As String, i As Long
s = Trim(CStr(Range("B1").Value))
DevTyp = IIf(Len(s) = 0, Null, s)
s = Trim(CStr(Range("B2").Value))
Descripcheck = IIf(Len(s) = 0, Null, s)
Set con = New ADODB.Connection
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\Database1.accdb;"
Set cmd = New ADODB.Command
cmd.ActiveConnection = con
cmd.CommandText = _
"SELECT COUNT(*) AS n FROM Site_Data " & _
"WHERE Device_Type " & IIf(IsNull(DevTyp), "IS NULL ", "= ? ") & _
"AND Description " & IIf(IsNull(Descripcheck), "IS NULL ", "= ? ")
i = 0
If Not IsNull(DevTyp) Then
cmd.CreateParameter "?", adVarWChar, adParamInput, 255
cmd.Parameters(i).Value = DevTyp
i = i + 1
End If
If Not IsNull(Descripcheck) Then
cmd.CreateParameter "?", adVarWChar, adParamInput, 255
cmd.Parameters(i).Value = Descripcheck
i = i + 1
End If
Set rst = cmd.Execute
Range("B6").Value = rst("n").Value
rst.Close
Set rst = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
End Sub

How to export spreadsheet data into SQLServer?

I am new to Vba, hope someone will solve my problem. I am trying to update data present in my spreadsheet. Actually i have 20,000 records, each record has around 74 columns. So updating them record by record by using ADO taking so much of time. Is there any alternative approach to update those records in single shot. Any help would be appreciated greatly.
Currently my code is.
Sub InitialExport()
On Error GoTo ErrHandler
Dim con As New ADODB.Connection
Dim Query As String
Dim EffectedRecs As Long
Dim i As Integer
ServerName = "192.178.78.36"
'Setting ConnectionString
con.ConnectionString = "Provider=SQLOLEDB; " & _
"Data Source=" & ServerName & "; " & _
"Initial Catalog=AppEmp;" & _
"User ID=sa; Password=admin08; "
'Setting provider Name
con.Provider = "Microsoft.JET.OLEDB.12.0"
'Opening connection
con.Open
With ThisWorkbook.Sheets("Export")
For i = 3 To ThisWorkbook.Sheets("Export").Range("B65536").End(xlUp).Row
'---------------------->
EmpId = .Range("B" & i).Value 'Emp Code-varchar
C = .Range("C" & i).Value 'Emp Name-varchar
D = .Range("D" & i).Value
E = .Range("E" & i).Value
F = .Range("F" & i).Value
G = .Range("G" & i).Value
H = .Range("H" & i).Value
II = .Range("I" & i).Value
JJ = .Range("J" & i).Value
k = .Range("K" & i).Value
l = .Range("L" & i).Value
M = .Range("M" & i).Value
N = CheckNull(.Range("N" & i).Value)
O = CheckNull(.Range("O" & i).Value)
P = CheckNull(.Range("P" & i).Value)
Q = CheckNull(.Range("Q" & i).Value)
R = CheckNull(.Range("R" & i).Value)
S = .Range("S" & i).Value
T = .Range("T" & i).Value
U = .Range("U" & i).Value
v = .Range("V" & i).Value
W = .Range("W" & i).Value
X = CheckNull(.Range("X" & i).Value)
Y = .Range("Y" & i).Value
Z = .Range("Z" & i).Value
AA = CheckNull(.Range("AA" & i).Value)
AB = .Range("AB" & i).Value
AC = CheckNull(.Range("AC" & i).Value)
AD = CheckNull(.Range("AD" & i).Value)
AE = CheckNull(.Range("AE" & i).Value)
AF = CheckNull(.Range("AF" & i).Value)
AG = .Range("AG" & i).Value
AH = CheckNull(.Range("AH" & i).Value)
AI = CheckNull(.Range("AI" & i).Value)
AJ = CheckNull(.Range("AJ" & i).Value)
AK = CheckNull(.Range("AK" & i).Value)
AL = CheckNull(.Range("AL" & i).Value)
AM = CheckNull(.Range("AM" & i).Value)
AN = CheckNull(.Range("AN" & i).Value)
AO = CheckNull(.Range("AO" & i).Value)
AP = CheckNull(.Range("AP" & i).Value)
AQ = CheckNull(.Range("AQ" & i).Value)
AR = CheckNull(.Range("AR" & i).Value)
aAS = CheckNull(.Range("AS" & i).Value)
AT = .Range("AT" & i).Value
AU = CheckNull(.Range("AU" & i).Value)
AV = CheckNull(.Range("AV" & i).Value)
AW = CheckNull(.Range("AW" & i).Value)
AX = CheckNull(.Range("AX" & i).Value)
AY = CheckNull(.Range("AY" & i).Value)
AZ = CheckNull(.Range("AZ" & i).Value)
BA = CheckNull(.Range("BA" & i).Value)
BB = CheckNull(.Range("BB" & i).Value)
BC = CheckNull(.Range("BC" & i).Value)
BD = CheckNull(.Range("BD" & i).Value)
BE = .Range("BE" & i).Value
BF = .Range("BF" & i).Value
BG = CheckNull(.Range("BG" & i).Value)
BH = .Range("BH" & i).Value
BI = .Range("BI" & i).Value
BJ = CheckNull(.Range("BJ" & i).Value)
BK = CheckNull(.Range("BK" & i).Value)
BL = CheckNull(.Range("BL" & i).Value)
BM = .Range("BM" & i).Value
BN = .Range("BN" & i).Value
Query = "Exec HRApp_P_AddEmpData '" & EmpId & "','" & C & "','" & D & "','" & E & "','" & F & "','" & G & "','" & H & "','" & II & "','" & JJ & "','" & k & "','" & l & "','" & M & "'," & N & "," & O & "," & P & "," & Q & "," & R & ",'" & S & "','" & T & "','" & U & "','" & v & "','" & W & "'," & X & ",'" & Y & "','" & Z & "'," & AA & ",'" & AB & "'," & AC & "," & AD & "," & AE & "," & AF & ",'" & AG & "'," & AH & "," & AI & "," & AJ & "," & AK & ",'" & AL & "'," & AM & "," & AN & "," & AO & "," & AP & "," & AQ & "," & AR & "," & aAS & ",'" & AT & "'," & AU & "," & AV & "," & AW & "," & AX & "," & AY & "," & AZ & "," & BA & "," & BB & "," & BC & "," & BD & ",'" & BE & "','" & BF & "'," & BG & ",'" & BH & "','" & BI & "'," & BJ & "," & BK & "," & BL & ",'" & BM & "','" & BN & "'"
con.Execute Query
Next
End With
con.Close
Set con = Nothing
Exit Sub
ErrHandler: 'MsgBox "The Not able ta Save Data"
Set con = Nothing
End Sub
The above code is working fine. But it is taking more time to update data.:-(
Now my code became like this
Private Sub Worksheet_Activate()
Dim adoConn As New ADODB.Connection
Dim adoRS As New ADODB.Recordset
Dim sQuery As String
Dim EffectedRecs As Long
Dim sFields As String
Dim sValues As String
Dim iRow As Integer
Dim iField As Integer
ServerName = "193.128.125.14"
con_Str = "Provider=SQLOLEDB; " & _
"Data Source=" & ServerName & "; " & _
"Initial Catalog=DB_At&T;" & _
"User ID=sa; Password=ad28; "
sQuery = "select * from Currency where 1=2"
sValues = ""
With adoConn
.ConnectionString = con_Str
.Provider = "Microsoft.JET.OLEDB.12.0"
.CursorLocation = adUseClient
.Open
End With
With adoRS
.ActiveConnection = adoConn
.CursorLocation = adUseClient
.LockType = adLockBatchOptimistic
.CursorType = adOpenKeyset ' adOpenDynamic
.Source = sQuery
.Open
End With
With ThisWorkbook.Sheets("Export")
For iRow = 3 To ThisWorkbook.Sheets("Export").Range("B65536").End(xlUp).Row
For iField = 0 To adoRS.Fields.Count - 1
sFields = sFields & "," & adoRS.Fields(iField).Name
Next
sValues = sValues & "," & .Range("A" & iRow).Value
sValues = sValues & "," & .Range("B" & iRow).Value
sValues = sValues & "," & .Range("C" & iRow).Value
sValues = sValues & "," & .Range("D" & iRow).Value
sFields = Right(sFields, Len(sFields) - 1) 'Removing ,
sValues = Right(sValues, Len(sValues) - 1) 'Removing ,
adoRS.AddNew FieldList = sFields, Values:=sValues
Next
End With
adoRS.UpdateBatch adAffectAllChapters
adoRS.Close
adoConn.Close
End Sub
you could try this:
Sub InitialExport()
On Error GoTo ErrHandler
'
Dim adoConn As New ADODB.Connection
Dim adoRS As ADODB.Recordset
'
Dim sQuery As String
Dim EffectedRecs As Long
Dim sFields As String
Dim sValues As String
'
Dim iRow As Integer
Dim iField As Integer
'
ServerName = SERVER_NAME
'
sQuery="SELECT * from tableName where 1 =2" ' get an empty recordset!
'
'Set the connection and open
with adoConn
.ConnectionString = CONNECTION_STRING
.Provider = "Microsoft.JET.OLEDB.12.0"
.cursorlocation=aduseclient
.Open
end with
'
' set the Recordset and open
With adoRS
.activeconnection=adoconn
.CursorLocation = adUseClient
.LockType = adLockBatchOptimistic
.CursorType = adopenkeyset ' adOpenDynamic
.Source = sQuery
.Open
End With
'
' now get the data into the recordset
With ThisWorkbook.Sheets("Export")
For iRow = 3 To ThisWorkbook.Sheets("Export").Range("B65536").End(xlUp).Row
' here loop through all the columns
For iField = 0 To adoRS.Fields.Count - 1
' adding the column names to the Variable sFields
sFields = sFields & "," & adoRS.Fields(iField).Name
'
' adding the values from the worksheet for this row
sValues = sValues & ", " & .Cells(iRow, iField).Text
Next
'
' add a new record with the fields and values
adoRS.AddNew FieldList:=sFields, Values:=sValues
'
Next
'
' update all the rows in one step
adoRS.UpdateBatch adAffectAllChapters ' update them all in one step!
'
End Sub
just change tablename in the query to the correct table and make sure the columns in the worksheet are in the same order and datatype as the columns in the table
for ADO Recordset help see:
MSDN Library - ADO Recordset, AddNew method
and
MSDN Library - ADO Recordset, UpdateBatch
and
W3Schools
I hope that get's you started!
Philip
Another option could be uploading your entire Excel Sheet as a csv file directly into the server using BulkInsert.
The Sql code might look as simple as this:
BULK INSERT [DB].[dbo].[Importa_Aux] FROM '\\share\filename.csv' WITH ( FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n' , FIRSTROW = 2 )
Then simply work your data updates in SqlServer.