First, sorry if my English is not that good; I am a trainee in software development and still learning English.
I made a virtual machine on vSphere with Oracle 19c and Windows Server 2016 64 bit and made an Excel file with macros on this machine. This Excel file is for our Customer to create invoices based on data from the Oracle database. Now our Customer should not perform on his server later when our software and database is delivered, instead he should do what he is doing on an external client which is maybe on the same network.
That is where the Problem starts, I copied the file on my laptop and changed the connection string the "HOST=..." part with the IP-Address from the VM. When I start the Sub a box appears with the message: [Microsoft][ODBC Driver Manager] The Datasourcename was not found, and no default driver specified.
Thank you for your help.
Private Sub Cmd1_Click()
'Variablen deklaration
Dim dbConnection As ADODB.Connection
Dim recordSet As ADODB.recordSet
Dim conString As String
Dim ipAddress As String
Dim port As String
Dim userId As String
Dim password As String
Dim driver As String
Dim dateFrom As String
Dim dateTo As String
Dim Query As String
Dim Lastrow1 As Long
Dim Lastrow2 As Long
'Vorhandene Daten löschen vor dem neuschreiben
Lastrow1 = ThisWorkbook.Sheets("Lagergeld").Range("B" &
Rows.Count).End(xlDown).Row
ThisWorkbook.Sheets("Lagergeld").Range("B3:H" & Lastrow1).Clear
Lastrow2 = ThisWorkbook.Sheets("Dienstleistungen").Range("B" &
Rows.Count).End(xlDown).Row
ThisWorkbook.Sheets("Dienstleistungen").Range("B3:H" & Lastrow2).Clear
Set dbConnection = New ADODB.Connection
' Variables are in a table in the same workbook
userId = Worksheets("Stammdaten").Range("Q4").Value
password = Worksheets("Stammdaten").Range("Q5").Value
ipAddress = Worksheets("Stammdaten").Range("Q6").Value '10.10.10.120
port = Worksheets("Stammdaten").Range("Q7").Value '1521
driver = Worksheets("Stammdaten").Range("Q8").Value ' {Oracle in
OraDB19Home1} tried several like {Microsoft ODBC for Oracle} and others
conString = "Driver=" & driver & ";" & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=" & ipAddress & ")(Port=" & port & "))" & _
"(CONNECT_DATA=(SERVICE_NAME=prod.world)));" & _
"user id=" & userId & ";password=" & password & ";)"
dbConnection.Open (conString)
dateFrom = Worksheets("Auswahl").Range("B12").Value
dateTo = Worksheets("Auswahl").Range("C12").Value
dateFrom = dateFrom & " 00:00:00"
dateTo = dateTo & " 23:59:59"
'Lagergeld
', VasStfCarrierFamilyTypes vscft
Query = " SELECT TO_CHAR(vsf.CreationTime, 'DD.MM.YYYY'), vscf.Name,
vscf.ReferenceHeight *" & _
" vscfh.Factor, vsf.TaxAttribute1, vsf.TaxAttribute2, vsf.Quantity,
vsf.TaxPoint " & _
" FROM VasStorageFee vsf, VasStfCarrierFamily vscf,
VasStfCarrierFamilyHeight vscfh" & _
" WHERE 1 = 1 " & _
" AND vsf.CreationTime >= TO_DATE('" & dateFrom & "', 'DD-MM-YYYY
HH24:MI:SS') " & _
" AND vsf.CreationTime <= TO_DATE('" & dateTo & "', 'DD-MM-YYYY
HH24:MI:SS')" & _
" AND vsf.OwnerCode = '" & Modul1.GetOwnerCode & "'" & _
" AND vsf.CarrierFamily = vscf.ID " & _
" AND vsf.EffectiveHeight = vscfh.ID " & _
" ORDER BY vsf.CreationTime ASC"
Set recordSet = dbConnection.Execute(Query)
ThisWorkbook.Sheets("Lagergeld").Activate
ThisWorkbook.Sheets("Lagergeld").Range("B3").CopyFromRecordset recordSet
ThisWorkbook.Sheets("Lagergeld").Range("B3").NumberFormat = "dd.mm.yyyy"
recordSet.Close
'Dienstleistungen
Query2 = " SELECT TO_CHAR(vsf.CreationTime, 'DD.MM.YYYY'), va.Description,
vsf.CarrierCode," & _
" vsf.MessageText, vsf.ArticleCode, vsf.Quantity, vsf.Taxpoint " &
_
" FROM VasServiceFee vsf, VasActivity va" & _
" WHERE 1 = 1" & _
" AND vsf.CreationTime >= TO_DATE('" & dateFrom & "', 'DD-MM-YYYY
HH24:MI:SS') " & _
" AND vsf.CreationTime <= TO_DATE('" & dateTo & "', 'DD-MM-YYYY
HH24:MI:SS')" & _
" AND vsf.OwnerCode = '" & Modul1.GetOwnerCode & "'" & _
" AND vsf.Activity = va.ID " & _
" ORDER BY vsf.CreationTime ASC"
Set recordSet = dbConnection.Execute(Query2)
ThisWorkbook.Sheets("Dienstleistungen").Range("B3").CopyFromRecordset
recordSet
ThisWorkbook.Sheets("Dienstleistungen").Range("B3").NumberFormat =
"dd.mm.yyyy"
recordSet.Close
dbConnection.Close
End Sub
solution was found, thanks to Eliton who made a comment on another issue. I have now installed the correct driver and adjusted the tnsnames.ora and the environment variables. With sqlplus and the ODBC - Manager from Microsoft I was able to connect successfully.
the only thing that was wrong was my connectionString
It has to be:
conString = "Driver={Oracle in instantclient_19_6}; DBQ=prod.world; PUID=myUser;" & _
"Pwd=myPassword"
Related
I am running a database in Access from within Excel VBA, using data from excel. When I use number as entry, say 12, on the field ClientID, it appends to the database from excel, even though the cell in which the field value is formatted as text and the data type of the CliendID field is set to TEXT(255).
When I change the value to "123ABC" it shows the message "Syntax error (missing operator) in query expression '123ABC'."
When I change the value to "ABC123" it shows the error message: "No value given for one or more required parameters."
I don't have much experience in SQL and have no clue why is this happening, one solution would be to change the clientID to numbers, but a lot of existing regiters I have are already alphanumeric.
The code is writen in excel vba.
Any help muchly appreciated.
Edit:
Sub CreateTables()
On Error GoTo ErrHandle
Dim strpath As String, constr As String
Dim objAccess As Object
Dim conn As Object
strpath = Worksheets("Sheet1").Range("strpathClients")
' CONNECT TO DATABASE '
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strpath & ";"
Set conn = CreateObject("ADODB.Connection")
conn.Open constr
conn.Execute "CREATE TABLE Clients (" _
& " ClientID TEXT(255)," _
& " ClientName TEXT(255)," _
& " Address TEXT(255)," _
& " Notes TEXT(255)," _
& " DateCreated DATETIME" _
& ");"
conn.Execute "CREATE TABLE Orders (" _
& " OrderID AUTOINCREMENT," _
& " ClientID TEXT(255)," _
& " Item TEXT(255)," _
& " Price DOUBLE," _
& " OrderDate DATETIME," _
& " Notes TEXT(255)" _
& ");"
' CLOSE CONNECTION '
conn.Close
Set conn = Nothing
MsgBox "Successfully created Clients and Orders tables!", vbInformation
Exit Sub
ErrHandle:
MsgBox Err.Number & " - " & Err.Description, vbCritical
Exit Sub
End Sub
Sub ActionQueriesAPPEND()
On Error GoTo ErrHandle
Dim strpath As String, constr As String
Dim conn As Object
strpath = Worksheets("Sheet1").Range("strpathClients")
' OPEN CONNECTION '
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strpath & ";"
Set conn = CreateObject("ADODB.Connection")
conn.Open constr
'MsgBox Worksheets(1).Range("A2")
' APPEND QUERY '
conn.Execute "INSERT INTO Clients (ClientID, ClientName)" _
& " VALUES (" & Worksheets(1).Range("A2") & ", '" &
Worksheets(1).Range("B2") & "');"
conn.Execute "INSERT INTO Orders (ClientID, Item, Price)" _
& " VALUES (" & Worksheets(1).Range("A2") & ", " _
& "'" & Worksheets(1).Range("C2") & "', " _
& Worksheets(1).Range("D2") & ");"
' CLOSE CONNECTION '
conn.Close
Set conn = Nothing
MsgBox "Successfully updated database!", vbInformation
Exit Sub
ErrHandle:
MsgBox Err.Number & " - " & Err.Description, vbCritical
Range("d24") = Err.Description
Exit Sub
conn.Execute "INSERT INTO Clients (ClientID, ClientName)" _
& " VALUES (" & Worksheets(1).Range("A2") & ", '" &
Worksheets(1).Range("B2") & "');"
missing single quotes around the value for ClientId
conn.Execute "INSERT INTO Clients (ClientID, ClientName)" _
& " VALUES ('" & Worksheets(1).Range("A2") & "', '" &
Worksheets(1).Range("B2") & "')"
I am trying to insert or update an external worksheet using SQL with VBA. Below the full function code.
The error happen when I try to open the recordset within the loop passing the sql select query.
Any help would be appreciated. I know that the connection string works as I am using it on other code.
The SQL string looks like this:
select top 1 VALUENAME FROM [TradingTotals$] WHERE LOWER(VALUENAME)= LOWER('Trading') AND VALUEDATE =29/05/2020 AND CLOSINGMONTH = 'May' ORDER BY VALUEDATE DESC)
Full Function code
Public Function InsertClosingMonthTotals(ByVal CollOfTradeLogTotObj As Collection) As Boolean
Dim IsSuccess As Boolean
Dim Item As TradeLogTotalsObj
Dim Sql As String
Dim SqlSelect As String
Dim ConnDbString As String
Dim TotalRecords As Long
Dim Name As String
Dim Value As Variant
Dim Trading As Variant
Dim LongShort As Variant
Dim Therms As Variant
Dim Valdate As Date
Dim ClosingMonth As String
ClosingMonth = Helper.FormatValue(Date, formatTypes.AsMonthlongOnly)
Set Glob_Conn = New ADODB.Connection
Set Glob_RecSet = New ADODB.Recordset
' Client-side cursor for correct return of record count
Glob_RecSet.CursorLocation = adUseClient
'Get Connection string according to the database server type
ConnDbString = Helper.GetConnectionString(ServerTypes.Excel, Glob_FilePathForDataInput)
'if the connection is closed then open it
If (Glob_Conn.State = 0) Then
Glob_Conn.Open (ConnDbString)
End If
For Each Item In CollOfTradeLogTotObj
Name = Item.Name
Value = Helper.FormatValue(Item.Value, AsNumber)
LongShort = Helper.FormatValue(Item.LongShort, AsDecimalThreeDigits)
Therms = Helper.FormatValue(Item.Therms, AsDecimalThreeDigits)
Valdate = Helper.FormatValue(Item.dateTime, AsDateDisplay)
SqlSelect = "select top 1 VALUENAME FROM [" & Glob_SheetNameTotalBooks & "$]" & _
" WHERE LOWER(VALUENAME)= LOWER(" & "'" & Name & "'" & ")" & " AND VALUEDATE =" & Valdate & _
" AND CLOSINGMONTH = " & "'" & ClosingMonth & "'" & _
" ORDER BY VALUEDATE DESC)"
Debug.Print ("SQL SELECT " & SqlSelect)
Debug.Print ("*************************************************************")
'open the record set
If (Glob_RecSet.State <> 1) Then
' ******* ERROR ON LINE BELOW ON OPEN **********
Glob_RecSet.Open SqlSelect, Glob_Conn, adOpenForwardOnly, adLockOptimistic
End If
TotalRecords = Glob_RecSet.RecordCount
If (TotalRecords > 0) Then
Sql = "UPDATE TradingTotals SET VALUENAME =" & "'" & Name & "'" & _
",VALUEDATE =" & Valdate & _
",VALUE =" & Value & _
",LONGSHORT =" & LongShort & _
",THERMS =" & Therms & _
",CLOSINGMONTH =" & "'" & ClosingMonth & "'" & _
" WHERE LOWER(VALUENAME) = LOWER(" & Name & ") AND VALUEDATE = " & Valdate & " AND CLOSINGMONTH =" & ClosingMonth
Else
Sql = "INSERT INTO " & Glob_SheetNameTotalBooks & " (VALUENAME,VALUEDATE,VALUE, LONGSHORT, THERMS, CLOSINGMONTH )" & _
" VALUES (" & "'" & Name & "'" & "," & Valdate & "," & Value & "," & LongShort & "," & Therms & "," & ClosingMonth & ")"
End If
Debug.Print ("SQL INSERT " & Sql)
Debug.Print ("*************************************************************")
Glob_Conn.Execute Sql
Next Item
'cleanup
Helper.CloseConnectionObjects Glob_RecSet, Glob_Conn
InsertClosingMonthTotals = IsSuccess
End Function
EDIT
this query works
SQL SELECT select TOP 1 VALUENAME FROM [TradingTotals$] WHERE LOWER(VALUENAME) ='Trading'
and seems that the issue is with LOWER() ; does anyone know if LOWER() cannot be used in excel queries?
EDIT 2
it seems that is just a matter of "properly" writing the query in Excel; this one below works. In the previous one tehre also was an extra ")" at the end of teh query
SQL SELECT select top 1 VALUENAME FROM [TradingTotals$] WHERE VALUENAME= 'Trading' AND VALUEDATE ='29/05/2020' AND CLOSINGMONTH = 'May' ORDER BY VALUEDATE DESC
I am trying now to use LOWER() again
EDIT 3
LOWER() dos not work, at least in the way I am using it in VBA;
SQL SELECT select top 1 VALUENAME FROM [TradingTotals$] WHERE LOWER(VALUENAME)='Trading' And ValueDate = '29/05/2020' AND CLOSINGMONTH = 'May' ORDER BY VALUEDATE DESC
I also tried double quotes for literals
So at the end there were different issues but mostly due with incorrect query syntax as I am writing SQL as when querying SQL server; not yet up to speed with excel query syntax.
Thanks to all who added useful comments, I am unaware on how to accept an answer from a comment so I am posting this as an answer but no credit to me at all; all credit to the great folks that added comments here.
I am now facing other issues with the insert.. basically even if I pass numbers as long and dates it get stored in excel as general. Even if I format the columns in the spreadsheet as date and number, it get reverted again to general?? but I am opening a new question for this issue
I'm getting the 462 runtime error when updating an Access table from Excel VBA. I think the references are correctly qualified with the object variable as described here and here, but I'm still getting an error on the line where the number of records is assigned to dbImageCount using DCount.
Run-Time error '462': The remote server machine does not exist or is unavailable
Public AppAccess As Access.Application
...
Sub btnSave2Access_Click()
Dim MyRow As Long, LastCaptionRow As Integer
Dim sPath As String, STblName As String, CatalogNum As String, LotNum As String
Dim i As Integer, dbImageCount As Integer
CatalogNum = Trim(Sheets("Tier2Worksheet").Range("B2"))
LotNum = Trim(Sheets("Tier2Worksheet").Range("B3"))
LastCaptionRow = Range("E1000").End(xlUp).Row
sPath = Sheets("Settings").Range("B16")
STblName = "tblProductPictures"
Set AppAccess = New Access.Application
With AppAccess
.OpenCurrentDatabase sPath
For i = 1 To LastCaptionRow
'error in next line
dbImageCount = DCount("[SortOrder]", STblName, "[CatalogNum] = '" & CatalogNum & "' AND [LotNum] = '" & LotNum & "'") 'get current image count in DB for catNum/LotNum combo
While dbImageCount < LastCaptionRow 'adds record to picture table when required
dbImageCount = dbImageCount + 1
.DoCmd.RunSQL "INSERT INTO " & STblName & " (CatalogNum, LotNum, SortOrder) VALUES ('" & CatalogNum & "','" & LotNum & "','" & dbImageCount & "');"
DoEvents
Wend
With .DoCmd
.SetWarnings False
.RunSQL "UPDATE " & STblName & " SET PicPath='" & Range("E" & i) & "' Where [CatalogNum]='" & CatalogNum & "' and [SortOrder]='" & i & "' and [LotNum]='" & LotNum & "';"
.RunSQL "UPDATE " & STblName & " SET FullCaption='" & Range("D" & i) & "' Where [CatalogNum]='" & CatalogNum & "' and [SortOrder]='" & i & "' and [LotNum]='" & LotNum & "';"
.SetWarnings True
End With
Next i
.CloseCurrentDatabase
.Quit
End With
Set AppAccess = Nothing
Application.StatusBar = False
End Sub
Manually setting the value of dbImageCount on the fly during debug (commenting out the DCount line) properly updates the database with the new picture data.
It's important to note that this problem does not occur consistently. After months of use, the error did not creep up until this week and even then it didn't happen for every update attempt. In addition, it never happened during development (on a different system).
At first, I thought it was a network glitch or something of the like, but then I read that the 426 error is specifically an Office automation problem, so I expect that we will see it again soon.
You need to use DCount as a method of the Access Application:
With AppAccess
.OpenCurrentDatabase sPath
For i = 1 To LastCaptionRow
'error in next line
dbImageCount = .DCount("[SortOrder]", STblName, "[CatalogNum] = '" & CatalogNum & "' AND [LotNum] = '" & LotNum & "'") 'get current image count in DB for catNum/LotNum combo
While dbImageCount < LastCaptionRow 'adds record to picture table when required
dbImageCount = dbImageCount + 1
.DoCmd.RunSQL "INSERT INTO " & STblName & " (CatalogNum, LotNum, SortOrder) VALUES ('" & CatalogNum & "','" & LotNum & "','" & dbImageCount & "');"
DoEvents
Wend
With .DoCmd
.SetWarnings False
.RunSQL "UPDATE " & STblName & " SET PicPath='" & Range("E" & i) & "' Where [CatalogNum]='" & CatalogNum & "' and [SortOrder]='" & i & "' and [LotNum]='" & LotNum & "';"
.RunSQL "UPDATE " & STblName & " SET FullCaption='" & Range("D" & i) & "' Where [CatalogNum]='" & CatalogNum & "' and [SortOrder]='" & i & "' and [LotNum]='" & LotNum & "';"
.SetWarnings True
End With
Next i
.CloseCurrentDatabase
.Quit
End With
Hello: I've had success with a long SQL (Oracle) as the Command Text in an OLEDB Data Connection that I entered manually. I then had success entering the SQL via VBA (because I need it to update based on a changing Item List), and only running the first part of the union query as a test.
However, when I made this last change adding a 2nd piece to the union query and making the strQuery command include three separate query strings, it's now throwing me an error at this line of the code below: .CommandText = StrQueryAll
StrQueryAll = StrQueryBegin & StrQueryAZ & StrQueryCO & StrQueryEnd
With ActiveWorkbook.Connections("connection_name").OLEDBConnection
.CommandText = StrQueryAll
.Refresh
End With
Below is the entire code with the actual sql removed. Is there an issue with the code for the sql too long? Or maybe another issue, but it's indirectly saying there's an error? Maybe it doesn't like strQueryAll command? I can do one big sql string with adding on strings with the continuation limitation, but thought it might be cleaner breaking up the sqls.
Thanks for your help!
Private Sub Refresh_Data()
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQueryAll As String
Dim StrQueryBegin As String
Dim StrQueryAZ As String
Dim StrQueryCO As String
Dim StrQueryCA As String
Dim StrQueryEnd As String
Dim Item_List As String
Dim wksItemList As Worksheet
Dim wksDataTable As Worksheet
Dim rngItems As Range
Dim rngDatatbl As Range
Dim myMSG As String
'Dim pt As PivotTable
myString = "Refreshing Tables - Please Wait"
Application.StatusBar = myString
'With Application
'.EnableEvents = False
'.ScreenUpdating = False
'End With
Set wksItemList = Worksheets("Items")
Set rngItems = wksItemList.Range("E4")
Set wksDataTable = Worksheets("data")
Set rngDatatbl = wksDataTable.Range("A3")
Item_List = rngItems.Value
StrQueryBegin = "SELECT " & Chr(13) & "" & Chr(10) & _
..... more sql....
.... next sql string ....
StrQueryAZ = " -- **** AZ ****" & Chr(13) & "" & Chr(10) & _
" select" & Chr(13) & "" & Chr(10) & _
..... more sql....
.... next sql string ....
StrQueryCO = Chr(13) & "" & Chr(10) & " UNION " & Chr(13) & "" & Chr(10) & _
" -- **** CO SYS ****" & Chr(13) & "" & Chr(10) & _
" select " & Chr(13) & "" & Chr(10) & _
..... more sql....
.... next sql string ....
StrQueryEnd = " ) " & Chr(13) & "" & Chr(10) & _
" ORDER BY " & Chr(13) & "" & Chr(10) & _
" ITEM_NBR, WHS " & Chr(13) & "" & Chr(10)
Debug.Print StrQueryBegin & StrQueryAZ & StrQueryCO & StrQueryEnd
StrQueryAll = StrQueryBegin & StrQueryAZ & StrQueryCO & StrQueryEnd
With ActiveWorkbook.Connections("connection_name").OLEDBConnection
.CommandText = StrQueryAll
.Refresh
End With
After doing more searching and tests, the problem is that the total CommandText characters has exceeded the allowable 32,767 chars.
user1274820: In a way, you were right where you needed to see the whole code. The sql is so long because of the way our tables are setup and the sql length is a necessary evil. I'll be looking into other options to run this.
I am trying to import and sort data from a large excel report into a new file using Excel 2007 VBA. I have come up with two methods so far for doing this:
Have Excel actually open the file (code below), gather all data into arrays and output the arrays onto new sheets in the same file and save/close it.
Public Sub GetData()
Dim FilePath As String
FilePath = "D:\File_Test.xlsx"
Workbooks.OpenText Filename:=FilePath, FieldInfo:=Array(Array(2, 2))
ActiveWorkbook.Sheets(1).Select
End Sub
Use ADO to get all data out of the closed workbook, import the whole datasheet into an array (code below) and sort data from there and then output data into a new workbook and save/close that.
Private Sub PopArray() 'Uses ADO to populate an array that will be used to sort data
Dim dbConnection As ADODB.Connection, rs As ADODB.Recordset
Dim Getvalue, SourceRange, SourceFile, dbConnectionString As String
SourceFile = "D:\File_Test.xlsx"
SourceRange = "B1:Z180000"
dbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=No"";"
Set dbConnection = New ADODB.Connection
dbConnection.Open dbConnectionString 'open the database connection
Set rs = dbConnection.Execute("SELECT * FROM [" & SourceRange & "]")
Arr = rs.GetRows
UpBound = UBound(Arr, 2)
rs.Close
End Sub
The test file used has about 65000 records to sort through (about a third of what I will end up using it for). I was kind of disappointed when the ADO version only performed marginally better than the open worksheet (~44 seconds vs ~40 seconds run time). I was wondering if there is some way to improve the ADO import method (or a completely different method - ExecuteExcel4Macro maybe? - if there is one) that would boost my speed. The only thing I could think of was that I am using "B1:Z180000" as my SourceRange as a maximum range that is then truncated by setting Arr = rs.GetRows to accurately reflect the total number of records. If that is what is causing the slow down, I'm not sure how I would go about finding how many rows are in the sheet.
Edit - I am using Range("A1:A" & i) = (Array) to insert data into the new worksheet.
This answer might not be what you are looking for but I still felt compelled to post it based on your side note [...] or a completely different method ]...].
Here, I am working with files of 200MB (and more) each which are merely text files including delimiters. I do not load them into Excel anymore. I also had the problem that Excel was too slow and needs to load the entire file. Yet, Excel is very fast at opening these files using the Open method:
Open strFileNameAndPath For Input Access Read Lock Read As #intPointer
In this case Excel is not loading the entire file but merely reading it line by line. So, Excel can already process the data (forward it) and then grab the next line of data. Like this Excel does not neet the memory to load 200MB.
With this method I am then loading the data in a locally installed SQL which transfers the data directly to our DWH (also SQL). To speed up the transfer using the above mething and getting the data fast into the SQL server I am transferring the data in chunks of 1000 rows each. The string variable in Excel can hold up to 2 billion characters. So, there is not problem there.
One might wonder why I am not simply using SSIS if I am already using a local installation of SQL. Yet, the problem is that I am not the one loading all these files anymore. Using Excel to generate this "import tool" allowed me to forward these tools to others, who are now uploading all these files for me. Giving all of them access to SSIS was not an option nor the possibility of using a destined network drive where one could place these files and SSIS would automatically load them (ever 10+ minutes or so).
In the end my code looks something like this.
Set conRCServer = New ADODB.Connection
conRCServer.ConnectionString = "PROVIDER=SQLOLEDB; " _
& "DATA SOURCE=" & Ref.Range("C2").Value2 & ";" _
& "INITIAL CATALOG=" & Ref.Range("C4").Value & ";" _
& "Integrated Security=SSPI "
On Error GoTo SQL_ConnectionError
conRCServer.Open
On Error GoTo 0
'Save the name of the current file
strCurrentFile = ActiveWorkbook.Name
'Prepare a dialog box for the user to pick a file and show it
' ...if no file has been selected then exit
' ...otherwise parse the selection into it's path and the name of the file
Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
Call Application.FileDialog(msoFileDialogOpen).Filters.Add("Extracts", "*.csv")
Application.FileDialog(msoFileDialogOpen).Title = "Select ONE Extract to import..."
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
strFileToPatch = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
Exit Sub
End If
'Open the Extract for import and close it afterwards
intPointer = FreeFile()
Open strFileNameAndPath For Input Access Read Lock Read As #intPointer
intCounter = 0
strSQL = vbNullString
Do Until EOF(intPointer)
Line Input #intPointer, strLine
If Left(strLine, 4) = """###" Then Exit Sub
'*********************************************************************
'** Starting a new SQL command
'*********************************************************************
If intCounter = 0 Then
Set rstResult = New ADODB.Recordset
strSQL = "set nocount on; "
strSQL = strSQL & "insert into dbo.tblTMP "
strSQL = strSQL & "values "
End If
'*********************************************************************
'** Transcribe the current line into SQL
'*********************************************************************
varArray = Split(strLine, ",")
strSQL = strSQL & " (" & varArray(0) & ", " & varArray(1) & ", N'" & varArray(2) & "', "
strSQL = strSQL & " N'" & varArray(3) & "', N'" & varArray(4) & "', N'" & varArray(5) & "', "
strSQL = strSQL & " N'" & varArray(6) & "', " & varArray(8) & ", N'" & varArray(9) & "', "
strSQL = strSQL & " N'" & varArray(10) & "', N'" & varArray(11) & "', N'" & varArray(12) & "', "
strSQL = strSQL & " N'" & varArray(13) & "', N'" & varArray(14) & "', N'" & varArray(15) & "' ), "
'*********************************************************************
'** Execute the SQL command in bulks of 1.000
'*********************************************************************
If intCounter >= 1000 Then
strSQL = Mid(strSQL, 1, Len(strSQL) - 2)
rstResult.ActiveConnection = conRCServer
On Error GoTo SQL_StatementError
rstResult.Open strSQL
On Error GoTo 0
If Not rstResult.EOF And Not rstResult.BOF Then
strErrorMessage = "The server returned the following error message(s):" & Chr(10)
While Not rstResult.EOF And Not rstResult.BOF
strErrorMessage = Chr(10) & strErrorMessage & rstResult.Fields(0).Value
rstResult.MoveNext
Wend
MsgBox strErrorMessage & Chr(10) & Chr(10) & "Aborting..."
Exit Sub
End If
End If
intCounter = intCounter + 1
Loop
Close intPointer
Set rstResult = Nothing
Exit Sub
SQL_ConnectionError:
Y = MsgBox("Couldn't connect to the server. Please make sure that you have a working internet connection. " & _
"Do you want me to prepare an error-email?", 52, "Problems connecting to Server...")
If Y = 6 Then
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = Ref.Range("C7").Value2
.CC = Ref.Range("C8").Value2
.Subject = "Problems connecting to database '" & Ref.Range("C4").Value & "' on server '" & Ref.Range("C2").Value & "'"
.HTMLBody = "<span style=""font-size:10px"">---Automatically generated Error-Email---" & _
"</span><br><br>Error report from the file '" & _
"<span style=""color:blue"">" & ActiveWorkbook.Name & _
"</span>' located and saved on '<span style=""color:blue"">" & _
ActiveWorkbook.Path & "</span>'.<br>" & _
"Excel is not able to establish a connection to the server. Technical data to follow." & "<br><br>" & _
"Computer Name: <span style=""color:green;"">" & Environ("COMPUTERNAME") & "</span><br>" & _
"Logged in as: <span style=""color:green;"">" & Environ("USERDOMAIN") & "/" & Environ("USERNAME") & "</span><br>" & _
"Domain Server: <span style=""color:green;"">" & Environ("LOGONSERVER") & "</span><br>" & _
"User DNS Domain: <span style=""color:green;"">" & Environ("USERDNSDOMAIN") & "</span><br>" & _
"Operating System: <span style=""color:green;"">" & Environ("OS") & "</span><br>" & _
"Excel Version: <span style=""color:green;"">" & Application.Version & "</span><br>" & _
"<br><span style=""font-size:10px""><br>" & _
"<br><br>---Automatically generated Error-Email---"
.Display
End With
Set OutMail = Nothing
Set OutApp = Nothing
End If
Exit Sub
SQL_StatementError:
Y = MsgBox("There seems to be a problem with the SQL Syntax in the programming. " & _
"May I send an error-email to development team?", 52, "Problems with the coding...")
If Y = 6 Then
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = Ref.Range("C8").Value2
'.CC = ""
.Subject = "Problems with the SQL Syntax in file '" & ActiveWorkbook.Name & "'."
.HTMLBody = "<span style=""font-size:10px"">" & _
"---Automatically generated Error-Email---" & _
"</span><br><br>" & _
"Error report from the file '" & _
"<span style=""color:blue"">" & _
ActiveWorkbook.Name & _
"</span>" & _
"' located and saved on '" & _
"<span style=""color:blue"">" & _
ActiveWorkbook.Path & _
"</span>" & _
"'.<br>" & _
"It seems that there is a problem with the SQL-Code within trying to upload an extract to the server." & _
"SQL-Code causing the problems:" & _
"<br><br><span style=""color:green;"">" & _
strSQL & _
"</span><br><br><span style=""font-size:10px"">" & _
"---Automatically generated Error-Email---"
.Display
End With
Set OutMail = Nothing
Set OutApp = Nothing
End If
Exit Sub
End Sub
i think that #Mr. Mascaro is right the easiest way to past your data from a Recordset into a spreadsheet is:
Private Sub PopArray()
.....
Set rs = dbConnection.Execute("SELECT * FROM [" & SourceRange & "]")
'' This is faster
Range("A1").CopyFromRecordset rs
''Arr = rs.GetRows
End Sub
but if you still want to use Arrays you could try this:
Sub ArrayTest
'' Array for Test
Dim aSingleArray As Variant
Dim aMultiArray as Variant
'' Set values
aSingleArray = Array("A","B","C","D","E")
aMultiArray = Array(aSingleArray, aSingleArray)
'' You can drop data from the Array using 'Resize'
'' Btw, your Array must be transpose to use this :P
Range("A1").Resize( _
UBound(aMultiArray(0), 1) + 1, _
UBound(aMultiArray, 1) + 1) = Application.Transpose(aMultiArray)
End Sub