VBA Excel code to retrieve data without opening a file - excel

I'm trying to get data from an excel workbook which is updated every month and the name of the file changes according to the date - I have an instructions page using the today function which gives me the month (this are the cell I'm referencing in "Month")
Problem is, the file I'm opening is very very big, and so this takes over 5 minutes just to start excel and copy the data. Is there anyway to modify my code to get the data without opening the excel file?
This is my code so far -
Sub UploadData()
Dim Model As Workbook
Dim Q As Workbook
Dim rngFX As Range
Dim Month As String
Set Model = ActiveWorkbook
Set Q = Workbooks.Open(Filename:=Sheets("Instructions").Range("$C$29").Value)
Month = ("C" & (Model.Sheets("Instructions").Range("$C$23")))
With Q
With .Sheets(Month & " Summary")
Set rngFX = .Range("A61:R66")
rngFX.Copy Destination:=Model.Sheets("FOREX Forecast").Range("A3")
End With
End With
Q.Close savechanges:=False
With Model.Sheets("FOREX Forecast").UsedRange
.Value = .Value
End With
End Sub
Edit: I've added a picture of the error I'm getting - When I press debug it highlights this line:
Rs.Open strSQL, strConn

Try
Sub UploadData()
Dim Model As Workbook
Dim Q As Workbook
Dim rngFX As Range
Dim Year As String
Dim Fn As String, wsName As String
Dim strConn As String
Dim strSQL As String
Dim Ws As Worksheet
Dim Rs As Object
Set Model = ActiveWorkbook
Set Ws = Model.Sheets("FOREX Forecast")
Fn = Sheets("Instructions").Range("$C$29").Value
'Set Q = Workbooks.Open(Filename:=Sheets("Instructions").Range("$C$29").Value)
Month = "C" & Model.Sheets("Instructions").Range("$C$23")
wsName = "[" & Month & " Summary" & "$" & "A61:R66 ]"
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & Fn & _
";Extended Properties=""Excel 12.0 Xml;HDR=NO;IMEX=1"";"
Set Rs = CreateObject("ADODB.Recordset")
strSQL = "select * from " & wsName
Rs.Open strSQL, strConn
Ws.Range("a3").CopyFromRecordset Rs
Rs.Close
Set Rs = Nothing
End Sub

Related

Connectionstring vba with blank space in dataname get broken

My Code is following. I'll try to copy a range of data from a closed sheet with connectionstrings. The Code is okay if the dataname hasn't a empty string.
e.g. test.xlsx is okay but test further.xlsx get broken.
'using sql
Sub ImportThisFile(FilePath As String, SourceSheet As String, Destination As Range)
Set Conn = New ADODB.Connection
'xls
'Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _
' FilePath & ";Extended Properties=Excel 8.0;"
'xlsx
Conn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & _
FilePath & ";Extended Properties=Excel 12.0 Xml;"
Sql = "SELECT * FROM [" & SourceSheet & "$] WHERE [fieldname] <> " & [""""""]
Set RcdSet = New ADODB.Recordset
RcdSet.Open Sql, Conn, adOpenForwardOnly
Destination.CopyFromRecordset RcdSet
RcdSet.Close
Set RcdSet = Nothing
Conn.Close
Set Conn = Nothing
End Sub
Sub StartDoingStuff()
Dim Zeit As Long, Anzahl As Long
Anzahl = 1
Zeit = Timer
Dim testvar As String, testvar2 As String, testvar3 As String
testvar = "C:\Users\Admin\Desktop\Folder\"
testvar2 = "testdata with emptystrings.xlsx.xlsx"
testvar2 = "test.xlsx"
testvar3 = "Tabelle1"
ImportThisFile testvar & testvar2, "Timesheet", Range(testvar3 & "!A2")
Debug.Print "Zeitbedarf"; Round(Timer - Zeit, 3)
End Sub
And Second Question.
If I want to copy a range, how i must write the code?
I need to determine the last cell in a column. How is that possible ?
the code i posted is correct. It was a mistake in the workbook (tablename)

VBA get sql result using column index from CSV Files

using vba macro I used the below query and I can able to get the results
strsQL = "SELECT name,address, balance1,balance2,balance3 FROM userInfo.csv"
if there any possibility to get the sql results using column index , instead of using column name (address) in VBA macro
Try it this way.
Sub GetMyCSVData()
Dim xlcon As ADODB.Connection
Dim xlrs As ADODB.Recordset
Set xlcon = New ADODB.Connection
Set xlrs = New ADODB.Recordset
Dim currentDataFilePath As String
Dim currentDataFileName As String
Dim nextRow As Integer
currentDataFilePath = "C:\My Data Folder\"
currentDataFileName = "My Data File"
xlcon.Provider = "Microsoft.Jet.OLEDB.4.0"
xlcon.ConnectionString = "Data Source=" & currentDataFilePath & ";" & "Extended Properties=""text;HDR=Yes;FMT=Delimited;"""
xlcon.Open
xlrs.Open "SELECT FirstName, Surname, Age FROM [" & currentDataFileName & ".csv] WHERE SomeNumber > 10", xlcon
xlrs.MoveFirst
nextRow = Worksheets("Sheet1").UsedRange.Rows.Count + 1
Worksheets("Sheet1").Cells(nextRow, 1).CopyFromRecordset xlrs
xlrs.Close
xlcon.Close
Set xlrs = Nothing
Set xlcon = Nothing
End Sub

Type mismatch Run time error-13 in VBA (showing error at Date Variable)

Here I'm getting error at
Dim strDate As Date
as type mismatch run time error..
Please any help will be appreciated....
Sub Insert11()
'click on tools and select Microsoft ActiveX data Objects 2.0 Library
Dim DBFullName As String
Dim Connect As String, Source As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Integer
Dim strDate As Date
Dim strWeight As Variant
Dim strMed_Id As Variant
Dim strGlucose As Variant
strDate = InsertForm.TextBox1.Value
strWeight = InsertForm.TextBox2.Value
strMed_Id = InsertForm.ListBox2.Value
strGlucose = InsertForm.TextBox3.Value
' InsertForm.Show
Cells.Clear
'Database path info
DBFullName = "C:\Users\ND5036832\Downloads\Assignment1234\Sample1.accdb"
'open the connection
Set Connection = New ADODB.Connection
Connect = "Provider=Microsoft.ACE.OLEDB.12.0;"
Connect = Connect & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Connect
'Create RecordSet
Set Recordset = New ADODB.Recordset
With Recordset
'filter Data
Source = "Insert into Glucose ([Date],Weight, Med_Id,Glucose) values ( " & strDate & "," & strWeight & "," & strMed_Id & "," & strGlucose & ");"
.Open Source:=Source, ActiveConnection:=Connection
'Msgbox " The query:" & vbNewLine & vbNewLine & Source
'Write field names
For Col = 0 To Recordset.Fields.Count - 1
Range("G1").Offset(0, Col).Value = Recordset.Fields(Col).Name
Next
'Write recordset
'Range("G1").Offset(1, 0).CopyFromRecordset Recordset
End With
ActiveSheet.Columns.AutoFit
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing
End Sub
Well, a TextBox contains Text (known as a String). If you try to put a String into a Date variable then I'm not surprised you get an error. Try:
strDate = CDate(InsertForm.TextBox1.Value)
This converts, or casts your string to a date. If you don't give it a string in date format it will, again, throw an error.
Furthermore. Be careful how you name your variables. strDate has "str" at the beginning to remind you that you're dealing with a String so you'd expect to see this:
Dim strDate As String
Since your variable will be in Date format, consider renaming it to something like:
Dim dtDate As Date
Or much better, ignore this Hungarian style naming convention and just name it something that has more meaning, like:
Dim selectedDate As Date

How to delete rows from excel files if a cell in a particular column contains the string of array?

I have many excel files in many folders and I need to delete the rows from all files where in column for ex. B are words from array:
For ex. my bad words list:
the sun, tree, big car, cup, ....
If A2 column is 'The Sun is the star at the center of the Solar System.' - this row has been deleted.
If in column is 'thesunis the..' - this row has been deleted. But is bad!
And my questions:
How to delete rows with exact words of array element?
How to count array elements?
How to escape single quote in array element (example in code below)
How to open all files from folder "C://folder" and after run code save all?
Here is my code:
Sub code()
Dim MyValue As String
Dim a As Integer
'------------------------------------------------------
ArrayValueToRemove = Array("the sun", "code 'in", "another")
Range("B:B").Select
'------------------------------------------------------
For Each cell In Selection
MyValue = CStr(cell.Value)
For a = 0 To 2
If InStr(1, LCase(MyValue), LCase(ArrayValueToRemove(a))) > 0 Then
cell.EntireRow.Delete
Exit For
End If
Next
Next cell
End Sub
Sub deleteBadWordRows()
Dim currentFile, currentSheet, badWords As Variant, lastRow, i As Integer, baseDirectory As String
'------------------------------------------------------
baseDirectory = "c:\folder\"
badWords = Array("the sun", "code 'in", "another")
'------------------------------------------------------
currentFile = Dir(baseDirectory)
While (currentFile <> "")
Workbooks.Open baseDirectory + currentFile
For Each currentSheet In Workbooks(currentFile).Worksheets
lastRow = currentSheet.Cells(currentSheet.Rows.Count, "B").End(xlUp).Row
For j = 1 To lastRow
For i = 0 To UBound(badWords)
If InStr(1, LCase(CStr(currentSheet.Cells(j, "B").Value)), LCase(badWords(i))) > 0 Then
currentSheet.Rows(j).Delete
j = j - 1
lastRow = lastRow - 1
Exit For
End If
Next
Next
Next
Workbooks(currentFile).Save
Workbooks(currentFile).Close
currentFile = Dir
Wend
End Sub
Consider an SQL solution to query your string searches using the LIKE operator with wildcard, %. Excel for PC can connect to the Jet/ACE SQL Engine (Window .dll files) and query workbooks. Here you avoid the nested looping except for iterating through workbooks.
Below assumes all worksheets are tabular in structure with column headers all beginning at A1. Query results are dumped to a new worksheet where you can delete current worksheet afterwards. Be sure to replace placeholders with actual names, CurrentWorksheet, ColumnA, NewWorksheet:
Sub DeleteSQL()
Dim conn As Object, rst As Object
Dim strConnection As String, strSQL As String
Dim i As Integer
Dim wb As Workbook
Dim dirpath As String: dirpath = "C:\\Folder"
Dim xlfile As Variant: xlfile = Dir(dirpath & "\*.xls*")
Do While (xlfile <> "")
Set wb = Workbooks.Open(dirpath & "\" & xlfile)
Set conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
' WORKBOOK CONNECTION
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='" & dirpath & "\" & xlfile & "';" _
& "Extended Properties=""Excel 8.0;HDR=YES;"";"
' OPEN DB CONNECTION
conn.Open strConnection
' OPEN RECORDSET
strSQL = " SELECT * FROM [CurrentWorksheet$]" _
& " WHERE [ColumnA] LIKE ""%the sun%"" OR [ColumnA]" _
& " LIKE ""%code 'in%"" OR [ColumnA] LIKE ""%another%"""
rst.Open strSQL, conn
wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count).Name = "NewWorkSheet"
' RESULTSET COLUMNS
For i = 1 To rst.Fields.Count
wb.Worksheets("NewWorkSheet").Cells(1, i) = rst.Fields(i - 1).Name
Next i
' RESULTSET DATA ROWS
wb.Worksheets("NewWorkSheet").Range("A2").CopyFromRecordset rst
wb.Close True
rst.Close: conn.Close
Set rst = Nothing: Set conn = Nothing
xlfile = Dir
Loop
End Sub

Need help creating a conditional copy macro for Excel 2003

I would like to conditionally copy data from multiple worksheets into a single worksheet in a given workbook in order to consolidate data. The macro would look at column F in all the worksheets, and if a row in column F matches a given number, that row gets copeid. Any help would be great!!
Terry
How about:
Dim cn As Object
Dim rs As Object
Dim ws As Worksheet
Dim wb As Workbook
Dim sSQL As String
Dim sFile As String
Dim sCon As String
Dim sXLFileToProcess As String
sXLFileToProcess = "Book1.xls"
strFile = Workbooks(sXLFileToProcess).FullName
'' Note that if HDR=No, F1,F2 etc are used for column names,
'' if HDR=Yes, the names in the first row of the range
'' can be used.
'' This is the Jet 4 connection string, you can get more
'' here : http://www.connectionstrings.com/excel
sCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
'' Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open sCon
'' In this example, the column header for column F is F, see notes
'' above on field (column) names. It also assumes that the sheets to
'' be merged have the same column headers in the same order
'' It would be safer to list the column heards rather than use *.
For Each ws In Workbooks(sXLFileToProcess).Worksheets
sSQL = sSQL & "SELECT * FROM [" & ws.Name & "$] " _
& "WHERE f=3 " _
& "UNION ALL "
Next
sSQL = Left(sSQL, Len(sSQL) - 10)
rs.Open sSQL, cn, 3, 3
'' New workbook for results
Set wb = Workbooks.Add
With wb.Worksheets("Sheet1")
'' Column headers
For i = 1 To rs.Fields.Count
.Cells(1, i) = rs.Fields(i - 1).Name
Next
'' Selected rows
.Cells(2, 1).CopyFromRecordset rs
End With
'' Tidy up
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

Resources