views:

130

answers:

1

Hi,

Need help. I have created the below as a macro so that a user can extract the info by clicking a single button:-

Sub Sales()

Dim StrSQl As String

Con = "Provider=IBMDA400;Data Source=XXX.XXX.XXX.XXX;User Id=yyyy;Password=zzzz"

Set Db = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.recordset")
Db.connectionSTring = Con
Db.Open
StrSQl = "select myuc, sum (myac) as Amount from myabc.myqwerty where mydt >= 20100101 and mydt <= 20100831 group by (mycl)"
rs.Open StrSQl, Db, 3, 3
Sheet2.Cells(1, 1).CopyFromRecordset rs
rs.Close
Set rs = Nothing
Set cn = Nothing
End Sub

Question, how can I create a 'box' within excel where a user can select the range of date (mydt >= 20100101 and mydt <= 20100831) before clicking the button ?

Thanks

A: 

in the VBA window, you can insert a UserForm. by clicking on the Insert Menu Item.

You can then add a couple of textboxes and a button to the form. Alternativly you could add a datepicker control which would be eaiser for the user to enter a correct date.

On the click event of the button you would retrieve the information from the textboxes. I would add a couple of parameters to the SQL string and add them to an ADO command object. you would end up with something like the following.

Sub Button1_Click()

    Dim strSql As String
    Dim cmd As ADODB.Command
    Dim db As ADODB.Connection
    Dim rs As ADODB.Recordset
    if IsDate(TextBox1.Text) and IsDate(TextBox2.Text) then
        Set db = New ADODB.Connection
        Set rs = New ADODB.Recordset
        Set cmd = New ADODB.Command

        db.ConnectionString = "Provider=IBMDA400;Data Source=XXX.XXX.XXX.XXX;User Id=yyyy;Password=zzzz"

        db.Open
        Set cmd.ActiveConnection = db
        strSql = "select myuc, sum (myac) as Amount from myabc.myqwerty where mydt >= ? and mydt <= ? group by (mycl)"
        cmd.CommandText = strSql
        cmd.CommandType = adCmdText
        cmd.Parameters(0).Value = CDate(TextBox1.Text)
        cmd.Parameters(1).Value = CDate(TextBox2.Text)
        Set rs = cmd.Execute

        Sheet2.Cells(1, 1).CopyFromRecordset rs

        rs.Close
        Set rs = Nothing
        Set db = Nothing
    Else
         MsgBox "Please ensure that you enter a Date in the to To and From boxes"
    End If
End Sub

Private Sub UserForm_Initialize()
    TextBox1.Text = DateTime.Date - 7
    TextBox2.Text = DateTime.Date + 1
End Sub

EDIT
I have updated the code by removing the named parameters and replacing with a question mark. this just makes it eaiser, as the command object creates the parameters for you, you just need to set the values. one thing to note is the order of parameters. I have executed this code in Excel 2007 the only thing I changed was the connection string and the SqlString. to verify that it works.

EDIT 2
Add a reference to Microsoft Activex Data Objects (ADO) via Tools -> References.

EDIT 3
Added some validation to ensure the user enters dates.

Edit 4
Added initialisation of the Textboxes to set some default dates from a week ago to today.

EDIT 5 Check that the Textbox name matches the one in the code. they should be the same. Demo Screen shot

Nathan Fisher
Bob
BTW, is there any order easy way to do the above ?
Bob
Sorry, typo error. It should be 'are there any other easier ways to the the above setting ?' Thanks.
Bob
When I added the Dim cmd As ADODB.Command Dim db As ADODB.Connection Dim rs As ADODB.Recordset, it prompted Compile Error : User-defined type not defined" under cmd As ADODB.Command
Bob
Sorry, forgot to include add a reference to Microsoft Activex Data Objects (ADO) via Tools -> References. You will find that there are multiple versions, I used ADO 2.8. the advantage of adding the reference is that it will give you compile time checking and also intellisense on the objects.
Nathan Fisher
Ok, I hv added that. Now, it prompted with Run-time error '424':Object required under cmd.Parameters(0).Value = CDate(TextBox1.Text)
Bob
Ok. my guess is that the Textbox1.text is what is causing the error. Is this sub/function on a userform? and is there 2 textboxes on the form?
Nathan Fisher
What userform ? I'm not aware of that at all. Sorry for asking but i'm pretty new to this. Do I need to create it 1st ?
Bob
Thats Ok. Happy to help. when you are editing the macro in the Visual Basic Editor go to menu Insert -> UserForm. this will give you a windows form designer. drag two textboxes on the form and a command button. this will form the basis for your "Box" that the user is able to enter the dates that they want. double click on the commandbutton, the designer will add a method that executes when the user clicks on it. assuming that you haven't renamed anything, you will have Textbox1, Textbox2 and Button1 which should line up with the code above hopefully.
Nathan Fisher
ok, I hv created the textboxes and a command button. Double click on the commandbutton1, i saw Private Sub CommandButton1_Click () End Sub. When I ran the process, it prompted with the same error msg:- Run=time error 424:Object required under cmd.Parameters(0).Value = CDate(TextBox1.Text
Bob
Ok we need to narrow down why you are getting this error. put a breakpoint on the line that is giving you the error, by selecting the line and pressing F9. also do a right click on Textbox1 and select `Add Watch` from the context menu. do the same for the `cmd` object. they should appear in the watch window usually in the bottom right of the screen. when you run the program, the progrm will stop on the breakpoint and the watch will display the current value of the objects being watched. in this case Textbox1 and cmd. the cmd object will have a `+` beside it.
Nathan Fisher
... click on it and you should see the current state of the properties. have a look at the Parameters wich should have a `+` beside it as well. expand it, hopefully the parameters count will be 2. hopefully you will have found where the error is coming from.
Nathan Fisher
another thing to try is to change the connection string to SQL Server database or access database and the SQL to a simple select with a date range just to confirm that it isn't something to do with the IBMDA400 oledb provider.
Nathan Fisher
Done that.Under watch windows, value is "Empty" for TestBox1. Expanding cmd, under Parameters, count is 2. I don't know what else to do. I don't even know how to identify the error, if any. Sorry but this is kinda too technical for me.
Bob
Bob
Ok it seems that the problem is with the textboxes. in the properties window on the left hand side towared the something What are the names of the textboxes on you form?
Nathan Fisher
One other thing to do is put this `Option Explicit` at the top of the code window. this will ensure that everything has bee declared upfront. and if it hasn't the code won't compile.
Nathan Fisher
Bob
Right. are the textboxes and the button on the same userform like the image above?
Nathan Fisher
yes, they are...
Bob
Bob - Have you had any luck with this? I can send you a demo or host it on github/bit bucket with it working as this is very difficult to try and debug via comments.
Nathan Fisher
I can't. I would really appreciate it if u can send me a demo [email protected] Thank You.
Bob