Microsoft Excel 2003 - copying out-of-order descriptions - excel

I have done a thorough search but cannot find an answer for my specific issue, using Microsoft Excel 2003.
I need to copy Column R descriptions (alphanumerical) from one xls spreadsheet (let's call it ssA) to columns L & M in another spreadsheet (ssB), by svc_itm_cde (service item code). There are about 300 svc_itm_cdes.
Three complications:
The svc_itm_cde column in ssA is not in the same order as the one in ssB.
Some of the rows of L & M in the ssB already contain descriptions and must be skipped.
Some of the svc_item_cdes in ssB do not appear in ssA, and vice versa.
A friend helped me export to cvs and begin a Python script, but that was too longwinded. Is there any way to do this with vba code (preferably)?
Many thanks.

This might be an over-complicated way of doing this for 300 records but it's a useful technique for larger datasets...
If you just need to get all of the data together in one place so you can work out which descriptions to keep and which to lose then you could use ADO and join the two data sets together.
Start by going to the Visual Basic Editor (press Alt+F11). Once there use Tools > References to add a reference to "Microsoft ActiveX Data Objects 2.8 Library"
Now Insert > Module and paste in this code:
Option Explicit
Sub master_list()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
' This is the connection string for .xlsx files (Excel 2007 and later)
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 12.0 Xml;"
.Open
End With
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM [ssA$] LEFT JOIN [ssB$] ON [ssA$].[svc_itm_cde] = " & _
"[ssB$].[svc_itm_cde] UNION ALL SELECT * FROM [ssA$] RIGHT JOIN [ssB$] ON " & _
"[ssA$].[svc_itm_cde] = [ssB$].[svc_itm_cde] " & _
"WHERE [ssA$].[svc_itm_cde] IS NULL;", cn
Dim i As Integer
Dim fld As ADODB.Field
i = 0
' Sheet3 should be a blank sheet that we can output the results to
With Worksheets("Sheet3")
For Each fld In rs.Fields
i = i + 1
.Cells(1, i).Value = fld.Name
Next fld
.Cells(2, 1).CopyFromRecordset rs
End With
rs.Close
cn.Close
End Sub
If you are using Excel 2003 or earlier then the connection string part should be:
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 8.0;"
.Open
End With

Related

Addressing a specific Access Form from Excel VBA

I have an Excel sheet with a command button, which opens an Access form and fills it with data from the sheet.
If I have two Access instances running (different databases) I get the message that VBA can not find the form.
Is it possible to address a specific database form?
Current Code: DoCmd.OpenForm ("FORM_ABC")
Not sure you need a Form to do this kind of thing. Here's one way to send data from Excel to Access.
Sub InsertIntoX2()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, row As Long
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=C:\Users\Excel\Desktop\Test.accdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "tblTrx", cn, adOpenKeyset, adLockOptimistic, adCmdTable
row = 3 ' the start row in the worksheet
Do While Not IsEmpty(Worksheets("Sheet1").Range("A" & row))
With rs
.AddNew ' create a new record
.Fields("ID") = Worksheets("Sheet1").Range("A" & row).Value
.Fields("Product") = Worksheets("Sheet1").Range("B" & row).Value
.Fields("ProdDate") = Worksheets("Sheet1").Range("C" & row).Value
.Update
End With
row = row + 1
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
If you want to use an Excel form to capture data and save the data to a Worksheet, and then send the results to Access, use the VBA code sample described above.

How to join two excel worksheets based on a column as key using VBA

I am not sure what approach to take but wondering can I join data from two excel sheets and populate in a 3rd sheet like how we join in SQL using VBA. Example data is below, I would like to join Sheet1 and Sheet2 by Emp_id and populate the result in Sheet3. I have googled a lot and tried whatever I know but nowhere I am close to get this, can someone throw some light on this or share an working example, that would be great. I am still trying and will post if I got a solution.
Below works for mine, again below query is for the sample data. For my actual data, I had to get the sheet number to use sheet name (example [Sheet2$] is replaced with [Sheet" & Sheets("Source").Index & "$] to use "Source" as the sheet in place of "Sheet2".
I have to use LEFT JOIN because I am getting error with only JOIN and later deleted the extra rows from Sheet3 for the records not matching in Sheet1, also you may have to use UNION function since FULL JOIN is not supported in case if you want data from both the table.
Hope this helps for someone...
Option Explicit
Sub JoinTables()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & ThisWorkbook.Name & ";" & _
"Extended Properties=Excel 8.0;"
.Open
End With
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM [Sheet2$] LEFT JOIN [Sheet1$] ON [Sheet2$].[Emp_id] = [Sheet1$].[Emp_id]", cn
With Worksheets("Sheet3")
.Cells(2, 1).CopyFromRecordset rs
End With
rs.Close
cn.Close
End Sub
cn As New ADODB.Connection
rec As New ADODB.Recordset
cn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & _
ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
SQLquery = "SELECT [Sheet2$].[Emp_id],[Sheet2$].[Hobies],[Sheet1$].[Salary] FROM [Sheet2$] INNER JOIN [Sheet1$] ON [Sheet2$].[Emp_id]=[Sheet1$].[Emp_id]"
rec.Open SQLquery, cn, adOpenKeyset, adLockOptimistic
Sheets("Sheet3").Range("A1").CopyFromRecordset rec

Is it possible to search for, then to read in specific values from an Excel file using Access VBA?

I have had to read in values from an excel file before, but it was a Excel comma separated file. This time I have an excel file with a graph and two tables. I only want to read in the values in one column of a specific table. Here is a picture of the layout of the excel file. I would like to read in the column marked "Amount" in the bottom table marked by a red arrow. I do not want to read in the total of all the amounts below it.
When I was reading in all values from a excel comma separated file I used this code. Initializations and unnecessary logic have been removed to only show the relevent code to this question.
Set objconnection = CreateObject("ADODB.connection")
Set objRecordset = CreateObject("ADODB.recordset")
objconnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strpathtotextfile & ";Extended Properties=""Text;HDR=YES;FMT=Delimited"""
objRecordset.Open "SELECT * FROM [" & ThisFileName & "]", objconnection, adOpenStatic, adLockOptimistic, adCmdText 'select all text lines from the file
Do While Not objRecordset.EOF 'read lines until end of file
'Clear out all the local objects so prior values aren't left there'
SampleName = ""
DateTimeAcquired = ""
Analyte = ""
Concentration = ""
'reads in each value according to column name and save to variable'
SampleName = objRecordset.Fields("Sample Name").Value
DateTimeAcquired = objRecordset.Fields("Date and Time Acquired").Value
Analyte = objRecordset.Fields("Element Full Name").Value
Concentration = objRecordset.Fields("Concentration").Value
'other logic'
objRecordset.MoveNext
Loop
Is there something similar I can do for the excel file I am currently trying to import? Is there a way to only import that one column?
UPDATE: the excel files are always in the same layout as in I am always retrieving information from slots 29G-34G.
You'll need to adjust the file path and sheet name, but something like this should work:
Sub Tester()
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\thisuser\Desktop\test.xlsx;" & _
"Extended Properties=""Excel 12.0 Xml;HDR=NO"""
Set rs = cn.Execute("select * from [Sheet1$G29:G34]")
Do While Not rs.EOF
Debug.Print rs(0).Value
rs.MoveNext
Loop
End Sub

Using ADODB in VBScript to find the number of rows in an Excel sheet?

I'm trying to use ADODB in VBScript to access an Excel file to find the number of rows in a given sheet that have data entered into them. My code so far displays everything on the sheet, but I'm not sure how I could count the rows or directly find the number of rows using a query. I want to use ADODB as it doesn't open the Excel file directly, but if this isn't the best way then how could I do it otherwise? Thanks.
Set adodb = CreateObject("ADODB.Connection")
adodb.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
"test.xls" & ";Extended Properties=""Excel 8.0;IMEX=1;" & _
"HDR=NO;" & """"
Set result = adodb.Execute("Select * from [Sheet1$]")
MsgBox result.GetString
result.Close
adodb.Close
Set adodb = Nothing
Set result = Nothing
Add a CursorLocation property for your Connection object.
Updated:
'result.CursorLocation = 3 'adUseClient
adodb.CursorLocation = 3 'adUseClient
Then you can get number of rows.
MsgBox result.RecordCount
I got this to work ok:
Sub testit()
Dim ad As New adodb.Connection
Dim result As New adodb.Recordset
ad.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=test.xls ;" & _
"Extended Properties=Excel 8.0;"
result.Open "Select count(*) FROM [Sheet1$]", _
ad, adOpenStatic, adLockOptimistic, adCmdText
Debug.Print "rows:" & result.GetString
result.Close
ad.Close
End Sub
(I changed your variable name adodb, as it seems to conflict).

asp and ms-access db - how to import data from xls file

i want to allow the user to upload xls file with 9 columns and unlimited number of rows.
i will run over everyline and insert the data to the db
how do i read the xls file?
You can read the XLS by opening an ADO recordset which pulls in the spreadsheet's data.
This example reads data from a spreadsheet named Billing Summary which includes column names in the first row..
Public Sub ReadSpreadsheet()
Const cstrFolder As String = "C:\Access\webforums"
Const cstrFile As String = "ExampleFinance.xls"
Dim strConnect As String
Dim strSql As String
Dim cn As Object
Dim rs As Object
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
cstrFolder & Chr(92) & cstrFile & _
";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strConnect
strSql = "SELECT * FROM [Billing Summary$] WHERE SomeField Is Not Null;"
rs.Open strSql, cn
Do While Not rs.EOF
'* do something with each row of data *'
'Debug.Print rs!SomeField '
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
If that particular connection string doesn't work for you, look at other examples of Excel connection strings at Connection strings for Excel
Edit: That example works in Access. But you said ASP. I think it will work there, too, if you drop the data types from the variable and constant declarations: Dim strSql instead of Dim strSql As String
Example of using an SQL statement to update Access from Excel.
Set cn = CreateObject("ADODB.Connection")
scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\docs\dbto.mdb"
cn.Open scn
sSQL = "SELECT * INTO NewTable FROM "
sSQL = sSQL & "[Excel 8.0;HDR=YES;IMEX=2;DATABASE=C:\Docs\From.xls].[Sheet1$]"
cn.Execute sSQL, recs
MsgBox recs
In C#, I had to load an excel spreadsheet to a DataSet - this got me there...
Code Project Example
I used Option 1 - the Preferred method! Hope this helps...
Mike

Resources