VBA to build blank Connection in Excel - excel

I am trying to build a blank SQL connection in Excel that will be updated with a connection string and command text a later point in the report.
Code I am trying to use:
Workbooks("WorkBook1.xlsm").Connections.Add2 "Test1", "Test1", " ", " ", "SQL"
Syntax from Microsoft:
Add2 (string Name, string Description, object ConnectionString, object CommandText, object lCmdtype, object CreateModelConnection, object ImportRelationships);
However, I am struggling with the syntax as I keep getting errors.
Any ideas?

So this isn't really an answer but rather a work around.
Sub Add_Connection()
Workbooks("WorkBook1.xlsm").Connections.AddFromFile _
"C:\Document\template_Connection.odc"
With ActiveWorkbook.Connections("template")
.Name = "Facility"
.Description = ""
End With
End Sub
I have a saved connection on my computer that I add and rename.

Related

Access Type conversion failure importing from Excel

I'm trying to import an Excel to Access DB, and some customer numbers cannot be imported due to Type Conversion Failure. It is 12 entries out of 66 thousand. Normally the customer number is a number, but these 12 are strings like ABCDEFT001. I tried setting the field of the table to Long Text or Short text, they are still not imported (only to ImportError table). Do you know what else I can try?
Thank you very much in advance!
P.S. I'm trying to import using DoCmd.TransferSpreadsheet
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Inv level", "Path/to/file.xlsb", True, "Sheetname!"
This strategy links to the excel file, instead of directly importing it, and then selects data out of it and casts any fields that need it to the correct datatype.
Sub ImportFromExcel()
Dim pathToFile As String
Dim targetTableName As String
Dim sql As String
pathToFile = "C:\Path\To\File.xlsx"
targetTableName = "ImportResults"
'//create the link
DoCmd.TransferSpreadsheet acLink, _
acSpreadsheetTypeExcel12, _
targetTableName, _
pathToFile, _
True '//This part only if the excel file has field headers
'//import
sql = "SELECT Field1Name, CStr(CustNumber) AS CustNumber, Field3Name INTO NewImportTable FROM " & targetTableName
CurrentDb.Execute sql
'//remove the link
DoCmd.DeleteObject acTable, targetTableName
End Sub
***Two pitfalls of this code to be aware of:
1) You should delete any table with the name "NewImportTable" before running this code, or you'll get a "Table Already Exists" error.
2) If any errors happen in this Sub before you remove the link, you'll have an issue the next time it runs, as it will create a link called "ImportResults1" since "ImportResults" would still exist. The really scary thing is that no errors would be thrown here. It would create "ImportResults1" and then run your sql on "ImportResults"!!

Evaluate statement (#DbLookUp) doesn't work with Lotusscript

The last week I asked how to solve an error in an evaluate statement (Error in Evaluate statement macro).
Once fix it, I have other error with the same evaluate statement, it doesn't give me any value.
I will describe what I have and what I try.
#DbLookup in Calculate Text
I have this code into in an calculate Text and it works fine.
suc := #Trim(#Left(LlcPoliza;2));
_lkp := _lkp := #DbLookup("":"NoCache";"C1256EAD:00478951";"People2"; "D"+suc; "FullName");
#If( #IsError( _lkp ) ; " " ; _lkp );
#Name([CN];_lkp)
LlcPoliza is a document field (doc.LlcPoliza) and in a document it has for example the value C2H2H2.
The formula give first the value C2 and then look up into People2 who is D+C2 and give me a person.
It works fine.
Evaluate Statement (#DbLookup) in a Class
I have a class DirectorSucursal.
Class DirectorSucursal
Private m_branch As String
'Constructor class
Public Sub New (branch)
Dim subString As String
subString = Left(branch, 2)
me.m_branch = subString
End Sub
'Deleter Class
Public Sub Delete
End Sub
'Sub show the code about Suc
Public Sub GetCodSuc
MsgBox m_branch
End Sub
'Function get the name director
Public Function getNameDirector As String
Dim varResult As Variant
varResult = Evaluate({#DbLookup("":"NoCache";"C1256EAD:00478951";"People2"; "D} & m_branch & {"; "FullName)"})
getNameDirector = CStr( varResult(0) )
End Function
End Class
Then, in a button I instantiate the new object DirectorSucursal with the parameter of the field doc.LlcPoliza(0) like this.
Sub Click(Source As Button)
Dim director As New DirectorSucursal(doc.LlcPoliza(0))
director.GetCodSuc
director.getNameDirector
end Sub
The field doc.LlcPoliza(0) has the value C2H2H2. GetCodSuc show the value C2, but the function getNameDirector doesn't work.
It shows the error:
Operation failed
Evaluate Statement (#DbLookup) in click button
I have tried the same but into a click sub.
Sub Click(Source As Button)
Dim subString As String
subString = Left(doc.LlcPoliza(0), 2)
Dim eval As String
eval = Evaluate({#DbLookup("":"NoCache";"C1256EAD:00478951";"People2"; "D} & subString & {"; "FullName)"})
Msgbox eval
End Sub
The field doc.LlcPoliza(0) has the value C2H2H2. But it doesn't work
It shows the error:
Operation failed
My question is: what am i doing wrong? Why the code works fine in a calculate text with #Formula but with Lotusscript not?
Thanks.
EDIT 1:
I have added and Error Goto, modified the class code, modified #dblookup in calculate text and I have this error:
Error in EVALUATE macro
Please read documentation and use help! evaluate always returns an ARRAY, as stated in the help:
Return value
variant
The result of the evaluation. A scalar result is returned.
To make your code return a STRING you need to change it like this:
Public Function getNameDirector As String
Dim varResult as Variant
varResult = Evaluate({#DbLookup("":"NoCache";"C1256EAD:00478951";"People2"; "D} & m_branch & {"; "FullName")})
getNameDirector = Cstr( varResult(0) )
End Function
The CStr is just there for the case where the #DBLookup returns an error or a number (both possible)
Just a few things in general:
NEVER write even one line of LotusScript- code without error handler. It will cause you trouble FOR SURE. If you had error handling in place, then it would have told you in which line the error occured...
NEVER use the result of #DBLookup without checking for #IsError... It will cause lot of troubles when the lookup fails.
IF you use #Iserror, then don't do the Lookup twice, assign the lookup to a variable and check that one for #Iserror, like this. Otherwise performance will go down in big forms:
Example:
_lkp := #DbLookup("":"NoCache";"C1256EAD:00478951";"People2"; "D"+suc; "FullName");
#If( #IsError( _lkp ) ; " " ; _lkp )
EDIT: As Knut correctly stated in his answer the real cause for the error was a typo in the formula ( Fullname)" instead of Fullname") that I fixed in my example as well.
1) My suggestion is to never (or at least very seldom) use Evaluate() in Lotusscript. You have proper Lotusscript functionality to do almost everything.
One of the major reasons is that the code is very hard to debug (which is what you are now experiencing).
2) Don't use extended notation when you work with fields. The best practice is to use the GetItemValue and ReplaceItemValue methods of the NotesDocument class for performance reasons as well as compatibility reasons.
3) In the examples with buttons you have a reference to doc, but it is never declared or initialized in the code. If you would use Option Declare at the top of your code you would catch these kinds of errors.
4) I also reccomend against using replica ID to reference databases, that makes it very hard to maintain in the future. Unless you have a very good and convincing reason, reference them by server and filename instead.
I would suggest you refactor your code to something like this:
'Function get the name director
Public Function getNameDirector() As String
Dim db as NotesDatabase
Dim view as NotesView
Dim doc as NotesDocument
Dim key as String
Dim fullname As String
Dim varResult As Variant
Set db = New NotesDatabase("Server/Domain","path/database.nsf")
If db Is Nothing Then
MsgBox "Unable to open 'path/database.nsf'"
Exit Function
End if
Set view = db.GetView("People2")
If view Is Nothing Then
MsgBox "Unable to access the view 'People2'"
Exit Function
End if
key = "D" & m_branch
Set doc = view.GetDocumentByKey(key)
If doc Is Nothing Then
MsgBox "Could not locate document '" & key & "'"
Exit Function
End if
fullname = doc.GetItemValue("FullName")(0)
End Function
Ando of course update the button actions in the same way.
Yes, it is a few lines longer, but it is much more readable and easier to maintain and debug. And you have error handling as well.
Change your last part in #DbLoookup code line to:
"FullName")})

Excel VBA Object Required ERROR

I have two lines of code that seems extremely easy, but excel keeps giving me this Compile error telling me that object is required?
So basically I want to get the current time, and replace the spaces with underscores so I can use this string as the name of my log fime.
Dim name As String
'EXCEL GIVE ME compile error: object required
name = Replace(FormatDateTime(Now, DateFormat.LONGTIME), " ", "_")
What's wrong?!!
Replacing DateFormat.LONGTIME to 'vbLongTime' works for me.
name = Replace(FormatDateTime(Now, vbLongTime), " ", "_")
You need to invoke Now as it is not a variable but a procedure
var now = str(Now());
name = Replace(FormatDateTime(now, DateFormat.LONGTIME), " ", "_")
should fix it

ADODB.Connection undefined

Reference Excel VBA to SQL Server without SSIS
After I got the above working, I copied all the global variables/constants from the routine, which included
Const CS As String = "Driver={SQL Server};" _
& "Server=****;" _
& "Database=****;" _
& "UID=****;" _
& "PWD=****"
Dim DB_Conn As ADODB.Connection
Dim Command As ADODB.Command
Dim DB_Status As Stringinto a similar module in another spreadsheet. I also copied into the same module
Sub Connect_To_Lockbox()
If DB_Status <> "Open" Then
Set DB_Conn = New Connection
DB_Conn.ConnectionString = CS
DB_Conn.Open ' problem!
DB_Status = "Open"
End If
End SubI added the same reference (ADO 2.8)
The first spreadsheet still works; the seccond at DB_Conn.Open pops up "Run-time error '-214767259 (80004005)': [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
Removing the references on both, saving files, re-opening, re-adding the references doesn't help. The one still works and the other gets the error.
?!?
I observed the same error message and in my case nothing had changed. I wondered if my odbc driver needed to be reinstalled (based on what i read online). In any case, restarting excel did the trick. Sometimes the solution is much simpler. :-)
When the error pops up, check your "locals" windows to see what the CS holds. View > Locals Window
Problem: Your constant isn't found by the compiler.
Solution: With the constant being located in a separate module, you'll need to set it as Public for the other code to see it.
Proof:
In order to prove this theory you can do the following:
Open a new Excel spreadsheet
Go to the VBA designer and add a new module
In this module put:
Const TestString As String = "Test String"
Then add the following code to ThisWorkbook:
Public Sub TestString()
MsgBox (TestString)
End Sub
After adding this return to the workbook and add a button, selecting "TestString" as the macro to run when clicked.
Click the button and a blank message box will appear.
Go back to the VBA designer and change the const in Module1 to Public
Click the button on the spreadsheet and you should now see "Test String" in the message box.
I realize that this question is really old. But for the record I want to document my solutions for the error here: It was a data related error in a spreadsheet! A column was formatted as date and contained a value 3000000. Changing the Format to numbers solved the Error 80004005.

Determining wrong input file using VBA & Excel

Any suggestions for determining if a user-selected Excel file is the incorrect one? I am having the user select the excel file to be parsed and I want to refuse processing it if appears to be an incorrect format.
If the file being parsed has headings, then check some of the text.
Sub ImportXYZ()
' ... Code to import
If ActiveWorkbook.Worksheets("Sheet1").Range("A1") <> "XYZ" Then
MsgBox CStr(ActiveWorkbook.Name) & vbCr & _
"The file you selected does not contain XYZ data!" & vbCr & "Please try again."
' ... Code to reset
Call ImportXYZ
End If
' ... Code to process import
End Sub
Put a hidden version field or other string in the excel file and break the execution if the string does not match. Assuming of course that you have control over the file or template, from which the file is created.
As an alternative to putting a marker that identifies the right type of file inside a worksheet, you can also use Workbook properties. Create a Custom property "MyExcelFilesClassification", and give the property a value like "MyTypeOfWorkbook". When your code opens the file, check that the Property has the right value, with something like:
Office.DocumentProperties customProperties = workbook.CustomDocumentProperties as Office.DocumentProperties;
foreach (Office.DocumentProperty property in customProperties)
{
if (property.Name == "MyExcelFilesClassification")
{
string modelType = property.Value as string;
if (modelType == "MyTypeOfWorkbook")
{
// do something
}
}
}
This is C# code, but the VBA or VB syntax shouldn't be very different.

Resources