Code works every other time in VBA - vba

The code below is programmed to retrieve data from a MS ACCESS 2010 Table and put it into a MS WORD 2010 Form b. The code works fine every time and throws NO error but opens the document and puts the data only every other time.
Sub Module11()
Dim appWord As Word.Application
Dim conn As ADODB.Connection
Dim doc As Word.Document
Dim rst As ADODB.Recordset
Dim tnum As String
Dim sname As String
Dim frst As Integer
Dim mrst As Integer
Dim sam As Integer
Dim strSQL As String
On Error Resume Next
Err.Clear
If Err.Number <> 0 Then
Set appWord = New Word.Application
End If
Set rst = New ADODB.Recordset
Set appWord = GetObject(, "Word.Application")
Set conn = New ADODB.Connection
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= D:\Database\Database.mdb"
rst.Open "tableSDR", conn, adOpenKeyset, adLockOptimistic
tnum = InputBox("Enter the Tracking Number of the Record " & _
"you want to find:", "TRACKING NUMBER")
strSQL = "Select * from table where rst!TrackingNumber='" & tnum & "'"
'AND " _
' & "[rst!TrackingNumber]='" & tnum & "' "
rst.Open strSQL, cn, adOpenDynamic, adLockReadOnly
sam = rst!TrackingNumber
Do While Not rst.EOF
If sam <> tnum Then
rst.MoveNext
sam = rst!TrackingNumber
Else
Exit Do
End If
Loop
Do While rst.EOF
MsgBox "Tracking Number Not Found! "
Exit Sub
Loop
Set doc = appWord.Documents.Open("D:\Database\Form.docx", True)
With doc
.FormFields("model").Result = rst!Model
.FormFields("date_submitted").Result = rst!TDate
.FormFields("part_number").Result = rst!PartNumber
.FormFields("sup_name").Result = rst!SupplierName
.FormFields("part_name").Result = rst!PartName
.FormFields("sup_location").Result = rst!SupplierLocation
.FormFields("rev_level").Result = rst!RevisionLevel
.FormFields("sup_contact").Result = rst!SupplierContact
.FormFields("po_number").Result = rst!PONumber
.FormFields("telephone_num").Result = rst!TelephoneNum
.FormFields("quantity").Result = rst!Quantity
.FormFields("fax_number").Result = rst!FaxNum
.FormFields("required_date").Result = rst!RequiredDate
.FormFields("dev_req").Result = rst!DeviationRequest
.FormFields("dev_period").Result = rst!DeviationPeriod
frst = rst!FirstTime
mrst = rst!MaterialChange
If (frst = 1) Then
If (mrst = 1) Then
doc.FormFields("time").Result = " Material Change and First Time"
ElseIf (msrt = 0) Then
doc.FormFields("time").Result = "First Time"
End If
ElseIf (frst = 0) Then
If (mrst = 1) Then
doc.FormFields("time").Result = " Material Change "
ElseIf (msrt = 0) Then
doc.FormFields("time").Result = "Not Applicable"
End If
End If
.FormFields("cur_spec").Result = rst!CurrentSPecification
.FormFields("prop_dev").Result = rst!ProposedDeviation
.FormFields("reason_dev").Result = rst!ReasonForDeviation
.FormFields("pur_sign").Result = rst!PurchaseSign
.FormFields("pur_des").Result = rst!PurchaseAD
.FormFields("pur_date").Result = rst!PurchaseDate
.FormFields("pur_com").Result = rst!PurchaseComments
.FormFields("qual_sign").Result = rst!QualitySign
.FormFields("qual_des").Result = rst!QualityAD
.FormFields("qual_date").Result = rst!QualityDate
.FormFields("qual_com").Result = rst!QualityComments
.FormFields("engg_sign").Result = rst!EnggSign
.FormFields("engg_des").Result = rst!EnggAD
.FormFields("engg_date").Result = rst!EnggDate
.FormFields("engg_com").Result = rst!EnggComments
.FormFields("manu_sign").Result = rst!ManuSign
.FormFields("manu_des").Result = rst!ManuAD
.FormFields("manu_date").Result = rst!ManuDate
.FormFields("manu_com").Result = rst!ManuComments
.FormFields("other_sign").Result = rst!OtherSign
.FormFields("other_des").Result = rst!OtherAD
.FormFields("other_date").Result = rst!OtherDate
.FormFields("other_com").Result = rst!OtherComments
.FormFields("doc_req").Result = rst!ChangeRequired
.FormFields("pca_number").Result = rst!PCANum
.FormFields("dis_comments").Result = rst!Comments
.FormFields("tracking_num").Result = rst!TrackingNumber
.Visible = True
.Activate
End With
doc.ActiveDocument.SaveAs (MSQname)
doc.Quit
Set doc = Nothing
Set rst = Nothing
Set appWord = Nothing
Set conn = Nothing
Exit Sub
errHandler:
MsgBox Err.Number & ": " & Err.Description
End Sub

I can't see any closure of the connection. The code falling over would cause it to close thus it would work the next time. try rs.close at then end.

Related

update if true and add new if false, criteria problem

Here is what i want: I'm making a code to generate invoices data automatically for me when i select month and year then click cmdbtn; but if customerID with the selected date ([Forms]![F_Reports_Slct]![MnthSlct]) and (....![YrSlct]) exists, then update the values instead of creating new record.
Everything here works fine except editing records if matched criteria..
my data is being recreated again when clicked.
I guess I have some problem with criteria.
Note that rsM and rsY are queries, and that the table's recordset ( rs ) has a primary key field with auto numbering [CrId].
Dim msg1 As Variant
Dim db As Database
Dim qdM As QueryDef
Dim qdY As QueryDef
Dim rs As Recordset
Dim rsM As Recordset
Dim rsY As Recordset
Dim lngID As Long
Dim Mcr As String
Dim Ycr As String
Dim strCriteria As String
If IsNull([Forms]![F_Reports_Slct]![YrSlct]) Or IsNull([Forms]![F_Reports_Slct]![MnthSlct]) Then
MsgBox "please enter data"
Cancel = True
Else
Set db = CurrentDb
Set qdM = db.QueryDefs("QC_MonthlyAm4CuID_Tr")
Set qdY = db.QueryDefs("QC_YrlyAm4CuID_Tr")
qdM.Parameters(0).Value = [Forms]![F_Reports_Slct]![YrSlct].Value
qdM.Parameters(1).Value = [Forms]![F_Reports_Slct]![MnthSlct].Value
qdY.Parameters(0).Value = [Forms]![F_Reports_Slct]![YrSlct].Value
qdY.Parameters(1).Value = [Forms]![F_Reports_Slct]![MnthSlct].Value
Mcr = qdM.Parameters(1).Value
Ycr = qdM.Parameters(0).Value
Set rs = db.OpenRecordset("T_CrofServices", dbOpenDynaset)
Set rsM = qdM.OpenRecordset(dbOpenDynaset)
Set rsY = qdY.OpenRecordset(dbOpenDynaset)
msg1 = MsgBox("sure?", vbYesNo + vbExclamation, "Are You Sure?")
If msg1 = vbNo Then
Cancel = True
ElseIf msg1 = vbYes Then
If Not rsM.BOF Then
rsM.MoveFirst
Do Until rsM.EOF
lngID = rsM!CuId & Mcr & Ycr
strCriteria = rs!TrDtCuID = " & lngID"
rs.FindFirst strCriteria
If rs.NoMatch Then
rs.AddNew
Else
rs.Edit
End If
rs![CuId] = rsM![CuId]
rs![CollectorID] = rsM![CollectorID]
rs![Amount] = rsM![MonthlyAm]
rs![DateofCr] = rsM![DateofCr]
rs![TrDtCuID] = rsM!CuId & Mcr & Ycr
rs![TrDt] = rsM![DtTr]
rs.Update
rsM.MoveNext
Loop
End If
If Not rsY.BOF Then
rsY.MoveFirst
Do Until rsY.EOF
lngID = rsY!CuId & Mcr & Ycr
strCriteria = "[TrDtCuID]=' & lngID'"
rs.FindFirst strCriteria
If rs.NoMatch Then
rs.AddNew
Else
rs.Edit
End If
rs![CuId] = rsY![CuId]
rs![CollectorID] = rsY![CollectorID]
rs![Amount] = rsY![YrlyAm1]
rs![DateofCr] = rsY![DateofCr]
rs![TrDtCuID] = rsY!CuId & Mcr & Ycr
rs![TrDt] = rsY![DtTr]
rs.Update
rsY.MoveNext
Loop
End If
rs.close
rsM.close
rsY.close
Set rs = Nothing
Set rsM = Nothing
Set rsY = Nothing
Set db = Nothing
Set qdM = Nothing
Set qdY = Nothing
MsgBox "Done.", vbInformation, "Succeed"
End If
End If
I guess I have some problem with criteria.
Yes. You must make up your mind, if you wish to use a Long or a String. Here, you are casting back and forth between these:
lngID = rsM!CuId & Mcr & Ycr
strCriteria = rs!TrDtCuID = " & lngID"
Also, it should read:
strCriteria = "TrDtCuID = " & lngID & ""
Or, if you turn the ID into a string:
strCriteria = "TrDtCuID = '" & strID & "'"

Excel VBA - writing Data from SQL/Recordset very slow

I am trying to write SQL Server data to an Excel sheet but it is very slow. Is there something to optimize? Approximately, 4000 entries at 20 cColumns takes 6-7 minutes.
Database ("freigabe") Module: Connecting to Database and get RecordSet
(this works like a charm)
Private Function ConnectSQL() As ADODB.Connection
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={SQL Server};" _
& "SERVER=xxxxx;" _
& " DATABASE=xxxxx;" _
& "UID=xxxxxx;PWD=xxxxx; OPTION=3"
conn.Open
Set ConnectSQL = conn
End Function
Public Function load(Optional ByVal FieldName As String = "", Optional ByVal fieldValue As String = "", Optional ByVal ComparisonOperator As String = "=")
'wenn fehler return?
'-> Über errorhandler retun rs oder boolen
Dim rs As New ADODB.Recordset
Dim sql As String
Dim contition As String
contition = " "
Dim sqlfrom As String
Dim sqlto As String
On Error GoTo Fehler:
sql = "SELECT * FROM " & TBLNAME & " WHERE storno='0' AND created BETWEEN '2020-02-01' AND '2020-02-15'"
Set conn = ConnectSQL()
rs.Open sql, conn, adOpenStatic
Set load = rs
Exit Function
End If
Fehler:
load = Err.Description
End Function
Get/Write: Build a connection and retrieving recordset. The While loop is taking long. I am skipping text-rich columns (it gets faster but still too long). Showing a load-window so the person doesn't think that Excel "isn't working". After that, the data get's validated (not included).
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim rs As Recordset
Dim k As Integer
Dim i As Integer
Dim startt As Double
Dim endt As Double
Dim rngDst As Range
Set rs = freigabe.load()
Set rngDst = Worksheets("Freigaben").Range("G2")
With Worksheets("Freigaben").Range("g2:Z50000")
.ClearContents
'.CopyFromRecordset rs
End With
Count = rs.RecordCount
k = 0
gui_laden.Show
startt = Timer
With rs
If Not .BOF And Not .EOF Then
.MoveLast
.MoveFirst
While Not .EOF
For i = 0 To .Fields.Count - 1
If i <> 13 And i <> 2 And i <> 10 And i <> 5 And i <> 6 And i <> 0 Then rngDst.Offset(, i) = .Fields(i).Value 'skip unneccessary data and write
Next i
k = k + 1
Debug.Print k & "/" & Count
gui_laden.lbl_status = "Lade Daten herunter: " & k & "/" & Count
gui_laden.Repaint
.MoveNext
DoEvents 'Ensure Application doesn't freeze
Set rngDst = rngDst.Offset(1)
Wend
End If
End With
endt = Timer - startt
Debug.Print "Dauer: " & endt
What I tried:
CopyFromRecordSet -> Application freezes
Test in new workbook -> same
Thank you very much!

Trying to make code more efficient and stable

I have a program, that works, I just feel that it is running slower than it should and I feel that it is a bit more unstable than it should be. I am looking for tips on writing "better" code and making my program more stable.
I am looking to better this part of my code for now:
Private Sub Worksheet_Activate()
Application.ScreenUpdating = False
'Removes shapes already there that will be updated by the getWeather function
For Each delShape In Shapes
If delShape.Type = msoAutoShape Then delShape.Delete
Next delShape
'Calls a function to get weather data from a web service
Call getWeather("", "Area1")
Call getWeather("", "Area2")
Call getWeather("", "Area3")
'Starting to implement the first connection to a SQL Access database.
Dim cn As Object
Dim rs As Object
'Set cn and sqlConnect as ADODB-objects. Set rs as recordset
Set cn = CreateObject("ADODB.Connection")
Set sqlConnect = New ADODB.Connection
Set rs = CreateObject("ADODB.RecordSet")
'Set sqlConnect as connection string
sqlConnect.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\databases\database.accdb;Persist Security Info=False;"
'Open connection string via connection object
cn.Open sqlConnect
'Set rs.Activeconnection to cn
rs.ActiveConnection = cn
'Get a username from the application to be used further down
Brukernavn = Application.userName
'This part of the code re-arranges the date format from american to european
StartDate = Date
EndDate = Date - 7
midStartDate = Split(StartDate, ".")
midEndDate = Split(EndDate, ".")
StartDate2 = "" & midStartDate(1) & "/" & midStartDate(0) & "/" & midStartDate(2) & ""
EndDate2 = "" & midEndDate(1) & "/" & midEndDate(0) & "/" & midEndDate(2) & ""
'SQL statement to get data from the access database
rs.Open "SELECT [RefNr], [Registrert Av],[Nettstasjon], [Meldt Dato] , [Bestilling], [Sekundærstasjon], [Avgang], [Hovedkomponent], [HovedÅrsak], [Status Bestilling] FROM [tblDatabase]" & _
"WHERE [Registrert Av] = '" & Brukernavn & "' AND [Loggtype] <> 'Beskjed' AND [Meldt Dato] BETWEEN #" & StartDate2 & "# AND # " & EndDate2 & "#" & _
"ORDER BY [Meldt Dato] DESC;", _
cn, adOpenStatic
'Start to insert data from access database into a list
Dim i As Integer
Dim u As Integer
If Not rs.EOF Then
rs.MoveFirst
End If
i = 0
With lst_SisteFeil
.Clear
Do
If Not rs.EOF Then
.AddItem
If Not IsNull(rs!refnr) Then
.List(i, 0) = rs![refnr]
End If
If IsDate(rs![Meldt Dato]) Then
.List(i, 1) = Format(rs![Meldt Dato], "dd/mm/yy")
End If
.List(i, 4) = rs![nettstasjon]
If Not IsNull(rs![Sekundærstasjon]) Then
.List(i, 2) = rs![Sekundærstasjon]
End If
If Not IsNull(rs![Avgang]) Then
.List(i, 3) = rs![Avgang]
End If
If Not IsNull(rs![Hovedkomponent]) Then
.List(i, 5) = rs![Hovedkomponent]
End If
If Not IsNull(rs![HovedÅrsak]) Then
.List(i, 6) = rs![HovedÅrsak]
End If
If Not IsNull(rs![Status Bestilling]) Then
.List(i, 7) = rs![Status Bestilling]
End If
If Not IsNull(rs![bestilling]) Then
.List(i, 8) = rs![bestilling]
End If
i = i + 1
rs.MoveNext
Else
GoTo endOfFile
End If
Loop Until rs.EOF
End With
endOfFile:
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
'Starts to connect to SQL access database again to get different set of data. This must be possible to make more efficient?
Dim cn2 As Object
Dim rs2 As Object
'Set cn and sqlConnect as ADODB-objects. Set rs as recordset
Set cn2 = CreateObject("ADODB.Connection")
Set sqlConnect2 = New ADODB.Connection
Set rs2 = CreateObject("ADODB.RecordSet")
'Set sqlConnect as connection string
sqlConnect2.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\databases\database.accdb;Persist Security Info=False;"
'Open connection string via connection object
cn2.Open sqlConnect
'Set rs.Activeconnection to cn
rs2.ActiveConnection = cn2
'Second SQL statement
rs2.Open "SELECT [RefNr], [Registrert Av],[Nettstasjon], [Meldt Dato] , [Bestilling], [Sekundærstasjon], [Avgang], [Hovedkomponent], [HovedÅrsak], [Status Bestilling] FROM [tblDatabase]" & _
"WHERE [Registrert Av] <> '" & Brukernavn & "' AND [Meldt Dato] BETWEEN #" & StartDate2 & "# AND # " & EndDate2 & "#" & _
"ORDER BY [Meldt Dato] DESC;", _
cn2, adOpenStatic
'Inserting into second list
If Not rs2.EOF Then
rs2.MoveFirst
End If
u = 0
With lst_AlleFeil
.Clear
Do
If Not rs2.EOF Then
.AddItem
If Not IsNull(rs2!refnr) Then
.List(u, 0) = rs2![refnr]
End If
If IsDate(rs2![Meldt Dato]) Then
.List(u, 1) = Format(rs2![Meldt Dato], "dd/mm/yy")
End If
.List(u, 4) = rs2![nettstasjon]
If Not IsNull(rs2![Sekundærstasjon]) Then
.List(u, 2) = rs2![Sekundærstasjon]
End If
If Not IsNull(rs2![Avgang]) Then
.List(u, 3) = rs2![Avgang]
End If
If Not IsNull(rs2![Hovedkomponent]) Then
.List(u, 5) = rs2![Hovedkomponent]
End If
If Not IsNull(rs2![HovedÅrsak]) Then
.List(u, 6) = rs2![HovedÅrsak]
End If
If Not IsNull(rs2![Status Bestilling]) Then
.List(u, 7) = rs2![Status Bestilling]
End If
If Not IsNull(rs2![bestilling]) Then
.List(u, 8) = rs2![bestilling]
End If
u = u + 1
rs2.MoveNext
Else
GoTo endOfFile2
End If
Loop Until rs2.EOF
End With
endOfFile2:
rs2.Close
cn2.Close
Set rs2 = Nothing
Set cn2 = Nothing
'Starting to connect to the database for the third time
Dim cn3 As Object
Dim rs3 As Object
'Set cn and sqlConnect as ADODB-objects. Set rs as recordset
Set cn3 = CreateObject("ADODB.Connection")
Set sqlConnect3 = New ADODB.Connection
Set rs3 = CreateObject("ADODB.RecordSet")
'Set sqlConnect as connection string
sqlConnect3.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\databases\database.accdb;Persist Security Info=False;"
'Open connection string via connection object
cn3.Open sqlConnect
'Set rs.Activeconnection to cn
rs3.ActiveConnection = cn3
'third sql statement
rs3.Open "SELECT [RefNr], [Registrert Av],[Nettstasjon], [Meldt Dato], [Sekundærstasjon], [Avgang], [Beskrivelse], [Til Dato] FROM [tblDatabase]" & _
"WHERE [Loggtype] = 'Beskjed' AND [Meldt Dato] >= DateAdd('d',-30,Date())" & _
"ORDER BY [Meldt Dato] DESC;", _
cn3, adOpenStatic
'Inserting data in to third list
If Not rs3.EOF Then
rs3.MoveFirst
End If
j = 0
With lst_beskjeder
.Clear
Do
If Not rs3.EOF Then
.AddItem
If Not IsNull(rs3!refnr) Then
.List(j, 0) = rs3![refnr]
End If
If IsDate(rs3![Meldt Dato]) Then
.List(j, 1) = Format(rs3![Meldt Dato], "dd/mm/yy")
End If
.List(j, 4) = rs3![nettstasjon]
If Not IsNull(rs3![Sekundærstasjon]) Then
.List(j, 2) = rs3![Sekundærstasjon]
End If
If Not IsNull(rs3![Avgang]) Then
.List(j, 3) = rs3![Avgang]
End If
If Not IsNull(rs3![beskrivelse]) Then
.List(j, 5) = rs3![beskrivelse]
End If
j = j + 1
rs3.MoveNext
Else
GoTo endOfFile3
End If
Loop Until rs3.EOF
End With
endOfFile3:
rs3.Close
cn3.Close
Set rs3 = Nothing
Set cn3 = Nothing
End Sub
Here is the function I have used to get weather data.
Public Sub getWeather(APIurl As String, sted As String)
Dim i As Integer
i = 0
Dim omraade As String
omraade = ""
omraade = sted
If sted = "Area1" Then
i = 4
ElseIf sted = "Area2" Then
i = 6
ElseIf sted = "Area3" Then
i = 8
End If
Dim WS As Worksheet: Set WS = ActiveSheet
Dim delShape As Shape
Dim city As String
Dim Req As New XMLHTTP
Req.Open "GET", "" & APIurl & "", False
Req.Send
Dim Resp As New DOMDocument
Resp.LoadXML Req.responseText
Dim Weather As IXMLDOMNode
Dim wShape As Shape
Dim thisCell As Range
For Each Weather In Resp.getElementsByTagName("current_condition")
Set thisCell = WS.Range(Cells(2, i), Cells(2, i))
Set wShape = WS.Shapes.AddShape(msoShapeRectangle, thisCell.Left, thisCell.Top, thisCell.Width, thisCell.Height)
wShape.Fill.UserPicture Weather.ChildNodes(4).Text 'img
Cells(3, i).Value = "" & Weather.ChildNodes(7).Text * 0.28 & " m/s" 'windspeedkmph
Cells(4, i).Value = Weather.ChildNodes(9).Text 'Direction
Cells(5, i).Value = Weather.ChildNodes(1).Text & " C" 'observation time
Next Weather
End Sub
Feel free to point out any poor coding and tips on how to improve it. I am currently using the Worksheet Activate sub to activate changes in the tables and get new data, but I suspect that is not the best solution. I am just not sure how else to do it seeing as I want it to be as "automatic" as possible, and use as few buttons to refresh as I can.
Thank you for all the help.
-Thomas
Some tips, but none will affect performance, only help make your code more succinct.
1.
rs.Open "SELECT ..."
If Not rs.EOF Then
rs.MoveFirst
End If
.MoveFirst is unnecessary. After opening a recordset, you are always on the first record, if there are records.
When building complex SQL in VBA, have a look at How to debug dynamic SQL in VBA.
2.
Don't do a Do ... Until loop for recordsets:
Do
If Not rs.EOF Then
' do stuff for each record
' ...
rs.MoveNext
Else
GoTo endOfFile
End If
Loop Until rs.EOF
endOfFile:
rs.Close
Instead use Do While Not rs.EOF :
Do While Not rs.EOF
' do stuff for each record
' ...
rs.MoveNext
Loop
rs.Close
For an empty rs, the loop will not be entered. You don't need the If/Else and the Goto.

How to make excel combobox.value triggering other textbox from access database

i have a combobox that have values from access database, how can i make the combobox as a trigger. When a value was chosen, then other textbox is automatically filled with corresponding value from access database? Thanks
On Error GoTo UserForm_Initialize_Err
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=E:\Database.accdb"
rs.Open "specification", cn, adOpenStatic
rs.MoveFirst
With Me.ComboBox1
.Clear
Do
.AddItem rs![SerialNoCubicle]
rs.MoveNext
Loop Until rs.EOF
End With
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
Exit Sub
this code for calling the values from database displayed in combobox
UPDATE
i found the solution but my code is pretty noob, need someone to help me simplify the code if it is possible
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
Dim sql1 As String
Dim sql2 As String
Dim sql3 As String
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ace.OLEDB.12.0; " & _
"Data Source=E:\Database.accdb"
Set rs = New ADODB.Recordset
sql1 = "Select * FROM specification Where SerialNoCubicle = '8'"
sql2 = "Select * FROM specification Where SerialNoCubicle = '17'"
sql3 = "Select * FROM specification Where SerialNoCubicle = '18'"
If TextBox8.Value = 8 Then
rs.Open sql1, cn
With rs
TextBox1.Value = rs.Fields("Project").Value
TextBox2.Value = rs.Fields("ProjectNo").Value
TextBox3.Value = rs.Fields("No&DateofDrw").Value
TextBox4.Value = rs.Fields("DrawingNumber").Value
TextBox5.Value = rs.Fields("NameofCubicle").Value
TextBox6.Value = rs.Fields("SingleLineLayout").Value
TextBox7.Value = rs.Fields("PlantofTest").Value
TextBox9.Value = rs.Fields("TypeofProduct").Value
TextBox10.Value = rs.Fields("IPofProduct").Value
TextBox11.Value = rs.Fields("Substation").Value
End With
End If
If TextBox8.Value = 17 Then
rs.Open sql2, cn
With rs
TextBox1.Value = rs.Fields("Project").Value
TextBox2.Value = rs.Fields("ProjectNo").Value
TextBox3.Value = rs.Fields("No&DateofDrw").Value
TextBox4.Value = rs.Fields("DrawingNumber").Value
TextBox5.Value = rs.Fields("NameofCubicle").Value
TextBox6.Value = rs.Fields("SingleLineLayout").Value
TextBox7.Value = rs.Fields("PlantofTest").Value
TextBox9.Value = rs.Fields("TypeofProduct").Value
TextBox10.Value = rs.Fields("IPofProduct").Value
TextBox11.Value = rs.Fields("Substation").Value
End With
End If
If TextBox8.Value = 18 Then
rs.Open sql3, cn
With rs
TextBox1.Value = rs.Fields("Project").Value
TextBox2.Value = rs.Fields("ProjectNo").Value
TextBox3.Value = rs.Fields("No&DateofDrw").Value
TextBox4.Value = rs.Fields("DrawingNumber").Value
TextBox5.Value = rs.Fields("NameofCubicle").Value
TextBox6.Value = rs.Fields("SingleLineLayout").Value
TextBox7.Value = rs.Fields("PlantofTest").Value
TextBox9.Value = rs.Fields("TypeofProduct").Value
TextBox10.Value = rs.Fields("IPofProduct").Value
TextBox11.Value = rs.Fields("Substation").Value
End With
End If
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
use the _change event
Private Sub ComboBox1_Change()
'or create your own query
qry = "SELECT [FIELD1] FROM [TABLE] WHERE [FIELD2] = " & Me.ComboBox1.value & ";"
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=E:\Database.accdb"
rs.open qry, cn
Me.Textbox1.Value = rs![FIELD1]
'rinse and repeat for other text boxes
rs.close
cn.close
End Sub

Import data to Excel by VBA and get the same style as do manually

I know how to connect excel to mysql manually, which is to click Data tab->From other sources->Data connection wizard...
The data loaded appear in this style. Note that by default the head line has a different background color than the lines below, and the background color of the other lines changes, the border color is white, etc.
I also learned how to import data by vba.
Sub ConnetMySQL()
Set conn = New ADODB.Connection
conn.ConnectionString = "Driver={MySQL ODBC 5.3 Unicode Driver};" & _
"Server = localhost; " & _
"Poer = 3306" & _
"Database = NBA;" & _
"UID = root; PASSWORD = ; OPTION=3"
conn.Open
Set rs = New ADODB.Recordset
strSQL = "SELECT * FROM `nba`.`game`"
rs.Open strSQL, conn
Dim myArray()
myArray = rs.GetRows()
kolumner = UBound(myArray, 1)
rader = UBound(myArray, 2)
For K = 0 To kolumner ' Using For loop data are displayed
Worksheets("Game").Range("a5").Offset(0, K).Value = rs.Fields(K).Name
For R = 0 To rader
Worksheets("Game").Range("A5").Offset(R + 1, K).Value = myArray(K, R)
Next
Next
rs.Close
'MsgBox strOutput
conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
But the data loaded by vba doesn't have any style.
I believe I must miss something in my code. How should I modify the code so that the data loaded by vba have the same style as the data loaded manually?
The below code will look for 1 table on the active sheet (assuming the ONLY information is the table). It does not matter about the size of the table. It will assume that there are headers. It will then format as your picture is formatted.
Sub test()
Set X = Sheets("Sheet1").UsedRange
ActiveSheet.ListObjects.Add(xlSrcRange, X, , xlYes).Name = _
"Table1"
X.Select
ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleMedium9"
End Sub
The below code is untested, but it should work for you:
Sub ConnetMySQL()
Set conn = New ADODB.Connection
conn.ConnectionString = "Driver={MySQL ODBC 5.3 Unicode Driver};" & _
"Server = localhost; " & _
"Poer = 3306" & _
"Database = NBA;" & _
"UID = root; PASSWORD = ; OPTION=3"
conn.Open
Set rs = New ADODB.Recordset
strSQL = "SELECT * FROM `nba`.`game`"
rs.Open strSQL, conn
Dim myArray()
myArray = rs.GetRows()
kolumner = UBound(myArray, 1)
rader = UBound(myArray, 2)
For K = 0 To kolumner ' Using For loop data are displayed
Worksheets("Game").Range("a5").Offset(0, K).Value = rs.Fields(K).Name
For R = 0 To rader
Worksheets("Game").Range("A5").Offset(R + 1, K).Value = myArray(K, R)
Next
Next
Set X = Sheets("Game").UsedRange
Sheets("Game").ListObjects.Add(xlSrcRange, X, , xlYes).Name = _
"Table1"
X.Select
Sheets("Game").ListObjects("Table1").TableStyle = "TableStyleMedium9"
rs.Close
'MsgBox strOutput
conn.Close
Set conn = Nothing
Set rs = Nothing
end sub