Please find below the code..
Function Connect_to_db(Byval mfgprt)
Dim cnn,rss
Set cnn = CreateObject("ADODB.Connection")
Set rss = CreateObject("ADODB.recordset")
cnn.ConnectionString = "DSN=QTPDSN;Description=desc;UID=;PWD=;APP=QuickTest Professional;WSID=;DATABASE=;"
cnn.open
rss = cnn.Execute (""select UnitPrice from ProductProfilePrices where MfPartNumber ='" + mfgprt + "'")
Connect_to_db=rss(0)
End Function
In this function, if I change a col name unit price in Query with '*' then it will return more than one value..in that case how to use rss .....
As if i'll do it(replace unit price with '*'),then while running it populates an error..in rss data fetching..
please by doing same modify the code.....
Thanks,
Galstar
You can refer to the fields by name, but first rss should be an object, so use Set, also the string concatenator is & :
Set rss = cnn.Execute (""select UnitPrice, Quantity " _
& " from ProductProfilePrices where MfPartNumber ='" & mfgprt & "'")
''Let us say that only one row is returned for mfgprt :
varUnitPrice = rss("UnitPrice")
varQuantity = rss("Quantity")
EDIT re comments
Connect_to_db "AAA", Val1, Val2
MsgBox Val1 & " " & Val2
Function Connect_to_db(ByVal mfgprt, ByRef Val1, ByRef Val2)
Dim cnn, rss
Set cnn = CreateObject("ADODB.Connection")
Set rss = CreateObject("ADODB.recordset")
cnn.ConnectionString = "DSN=QTPDSN;Description=desc;" _
& "UID=;PWD=;APP=QuickTest Professional;WSID=;DATABASE=;"
cnn.Open
rss = cnn.Execute("select UnitPrice, Quantity " _
& " from ProductProfilePrices where MfPartNumber ='" & mfgprt & "'")
Val1 = rss(0)
Val2 = rss(1)
End Function
Related
when I m trying to set Recordset using oracle connection string, I m getting OUt of memory error.
on line "rsLIS.Open sql, gConnLIS, adOpenStatic, adLockReadOnly"
However some time it works like once in 5-6 attempts
but when it works it gives error on some other line
on line "If rsLink.Fields(2).value = rsLIS.Fields(1).value Then"
here are the things which I tried :
instead of directly using recordset, I tried to create array (GetRows) method.
Even though recordset count is 26 but UBound of array is showing 1
I have trying changing 3rd argument value from static to forward only
in line ""rsLIS.Open sql, gConnLIS, adOpenStatic, adLockReadOnly""
it also didn't work, it was showing recordset.count as 0
Did try after restarting the client system still same
I m getting this error on client side and since at my place I don't have development environment to debug
Error is "OUT OF MEMORY"
Public Function GetResults_New(MachName As String, patid As String, bCheckDate As Boolean, SendAssay As Boolean) As ADODB.Recordset
On Error GoTo errdesc
Call ShowTempMsg("Line 1")
Dim bXVar As Boolean
Dim i, j As Integer
Dim tmplis, tmporder
Dim tmpresult
bXVar = False
Dim rec_result As New ADODB.Recordset
Dim rsLink As New ADODB.Recordset
Dim rsLIS As New ADODB.Recordset
Dim xSampleIdType As String
gAppPath = AddEditINIfile("VAHSIF.INI", "IF", "sLinkPath", "")
xSampleIdType = AddEditINIfile(gAppPath & "\sLinkConfig.ini", MachName, "SampleIdType", "SampleId1", False)
Call Open_Connection
Call Open_Connection_LIS
rec_result.CursorLocation = adUseClient
If SendAssay = True Then
rec_result.Fields.Append "machineparamid", adBSTR, 50
rec_result.Fields.Append "Assayno", adBSTR, 50
rec_result.Fields.Append "SType", adBSTR, 50
rec_result.Fields.Append "Dilution", adBSTR, 50
Else
rec_result.Fields.Append "machineparamid", adBSTR, 50
rec_result.Fields.Append "SType", adBSTR, 50
rec_result.Fields.Append "Dilution", adBSTR, 50
End If
rec_result.Open
\
'Link Query For Mapped Params.
sql = "SELECT EquipParamMapping.EquipId, EquipParamMapping.EquipParamCode, EquipParamMapping.LISParamCode, EquipParamMapping.EquipAssayNo from EquipParam, EquipParamMapping where equipParam.equipid = equipparammapping.equipid and equipparam.equipparamcode = equipparammapping.equipparamcode and EquipParam.EquipID = '" & MachName & "' and EquipParam.isProgram = 'Y'"
**rsLink.Open sql, gConn, adOpenStatic, adLockReadOnly**
If enumConnTo = connOracle Then
sql = "select " & xSampleIdType & " , LIS_Param_Code From SL_21CI_View_sampleid_Orders where " & xSampleIdType & " || SuffixCode = '" & patid & "' and isApplicable <> 'N' "
Else
sql = "select " & xSampleIdType & " , LIS_Param_Code From SL_21CI_View_sampleid_Orders where " & xSampleIdType & " + cast(SuffixCode as varchar(20)) = '" & patid & "' and isApplicable <> 'N' "
End If
rsLIS.Open sql, gConnLIS, adOpenStatic, adLockReadOnly
While Not rsLIS.EOF
If bXVar = True Then
rsLink.MoveFirst
bXVar = False
End If
While Not rsLink.EOF
bXVar = True
**If rsLink.Fields(2).value = rsLIS.Fields(1).value Then**
If SendAssay = True Then
rec_result.AddNew
rec_result("machineparamid") = rsLink.Fields("EquipParamCode")
rec_result("Assayno") = rsLink.Fields("EquipAssayNo")
rec_result("SType") = " "
rec_result("Dilution") = "0"
rec_result.Update
rec_result.MoveFirst
Else
rec_result.AddNew
rec_result("machineparamid") = rsLink.Fields("EquipParamCode")
rec_result("SType") = " "
rec_result("Dilution") = "0"
rec_result.Update
rec_result.MoveFirst
End If
GoTo NextParam
End If
rsLink.MoveNext
Wend
NextParam:
rsLIS.MoveNext
Wend
Set GetResults_New = rec_result
Exit Function
errdesc:
Call InsertIntoLogWithFileName("Transaction.GetResults_New" & vbNewLine & sql & vbNewLine & err.Description & "ErrLine : " & ErrLine)
End Function
Thanks
That still leaves the question on which line the error occurs. Also: "it also didn't work, it was showing recordset.count as 0". The RecordSet.Count property depends on the provider. Use a function similar to this instead:
Public Function RecordCount(ByVal cn As ADODB.Connection, ByVal sTable As String) As Long
Dim sSQL As String, lRetVal as Long
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
sSQL = "SELECT COUNT(1) AS RecCount FROM " & sTable & ";"
Call rs.Open(sSQL, cn)
If Not (rs.BOF And rs.EOF) Then
lRetVal = rs.Fields("RecCount").Value
Else
lRetVal = -1
End If
Call rs.Close
Set rs = Nothing
RecordCount = lRetVal
End Function
The .Count property might also very well be the cause of the Out of memory error, as I seem to remember that for determing the number of records, it loads all records (from the server) to count them. But I might be wrong there.
I added a filter method which is filter by department by select the combo box options, however, I have no idea about how to push the data into the list after query from database. Below is my code.
Private Sub comboDept_Click()
Dim sQuery As String
Dim oRS As New ADODB.Recordset
Dim oRS_PR As New ADODB.Recordset
Dim sPONO As String
Dim sPOAmt As String
combVal = comboDept.List(comboDept.ListIndex)
If combVal = "EIBU_SALES" Then
sQuery = "Select PO_No, PO_Requestor, PO_Req_Dept, PO_Status, PO_Approval_M, PO_Approval_GM, PO_Approval_D, PO_HRApproval, VC_No, TH_Sup_Inv, PO_HR_Rmk, PO_Req_Date, PO_SupplierName, PO_OverallAmt from PR_INFO where PO_Req_Dept = '" & combVal & "'"
oRS_PR.Open sQuery, PRCnn, adOpenDynamic, adLockOptimistic
ElseIf comboDept.List(comboDept.ListIndex) = "MCBU_SALES" Then
Try something like this (it's just a hint; you have to adjust the code):
' Empty list
myListView.ListItems.Clear
' Add items
While (Not oRS_PR.EOF)
Set item = myListView.ListItems.Add(, , oRS_PR!FIRST_COLUMN)
item.SubItems(...) = oRS_PR!SOME_COLUMN
item.SubItems(...) = oRS_PR!OTHER_COLUMN
oRS_PR.MoveNext
Wend
i'm in the process of roughing out a proof of concept for desktop software i'd like to develop. I'm using Access 2013.
The following code is supposed to analyse records in one table ('tblRestructures') and depending on the analysis it should then populate records in another table ('tblInScopeRestructures'). The sample data in tblRestructures is set up such that the code should cause there to be records with field(Gen) with values 1 to 6 inclusive. Sometimes the code does succeed in populating tblInScopeRestructures as expected but other times the code ends early (ie conditions for ending various loops are met). Despite a lot of time spent trying to identify the cause of the variability and looking for similar questions here, I am still none the wiser.
Any help here is gratefully received. And I apologise up front for my ugly code - I am not experienced and at this stage I am just trying to speed through a proof of concept.
Here is the code:
Public Function NbrOfShares3(strCode As String, dteDate As Date) As Single
Dim i As Integer
Dim strPrevCode1 As String
Dim adConn As ADODB.Connection
Set adConn = New ADODB.Connection
adConn.Open CurrentProject.Connection
Dim adrsa As ADODB.Recordset
Set adrsa = New ADODB.Recordset
adConn.Execute "DELETE * from tblInScopeRestructures"
adrsa.ActiveConnection = CurrentProject.Connection
adrsa.CursorType = adOpenStatic
' Identify all gen 1 (Code1 = CODE) restructures up to dteDate and put in a temp table
adrsa.Open "SELECT tblRestructure.Code1, tblRestructure.Code2, tblRestructure.RecDate " & _
"FROM tblRestructure " & _
"WHERE (((tblRestructure.Code1)='" & strCode & "')) AND (((tblRestructure.RecDate)<=#" & Format(dteDate, "mm/dd/yyyy") & "#));"
If adrsa.RecordCount <> 0 Then
adrsa.MoveFirst
Do While Not adrsa.EOF
adConn.Execute ("INSERT INTO tblInScopeRestructures(Code1,Code2,RecDate,Gen) VALUES ('" & adrsa.Fields("Code1") & "','" & adrsa.Fields("Code2") & _
"',#" & Format(adrsa.Fields("RecDate"), "mm/dd/yyyy") & "#," & 1 & ")")
adrsa.MoveNext
Loop
End If
i = 0
'Identify all code1 in
Dim adrsb As ADODB.Recordset
Set adrsb = New ADODB.Recordset
adrsb.ActiveConnection = CurrentProject.Connection
Do
i = i + 1
If adrsb.State = 1 Then
adrsb.Close
End If
adrsb.CursorType = adOpenStatic
adrsb.Open "SELECT tblInScopeRestructures.Code1, tblInScopeRestructures.Gen " & _
"FROM tblInScopeRestructures " & _
"GROUP BY tblInScopeRestructures.Code1, tblInScopeRestructures.Gen " & _
"HAVING (((tblInScopeRestructures.Gen)=" & i & "));"
Dim adrsc As ADODB.Recordset
Set adrsc = New ADODB.Recordset
adrsc.ActiveConnection = CurrentProject.Connection
adrsc.CursorType = adOpenStatic
If Not adrsb.EOF Then
adrsb.MoveLast
adrsb.MoveFirst
End If
If adrsb.RecordCount <> 0 Then
adrsb.MoveFirst
strPrevCode1 = adrsb.Fields("Code1")
Do While Not adrsb.EOF
If adrsc.State = 1 Then
adrsc.Close
End If
adrsc.CursorType = adOpenStatic
adrsc.Open "SELECT tblRestructure.Code1, tblRestructure.Code2, tblRestructure.RecDate " & _
"FROM tblRestructure " & _
"WHERE (((tblRestructure.Code2)='" & strPrevCode1 & "'));"
If adrsc.RecordCount <> 0 Then
adrsc.MoveFirst
Do While Not adrsc.EOF
adConn.Execute ("INSERT INTO tblInScopeRestructures(Code1,Code2,RecDate,Gen) VALUES ('" & adrsc.Fields("Code1") & "','" & adrsc.Fields("Code2") & _
"',#" & Format(adrsc.Fields("RecDate"), "mm/dd/yyyy") & "#," & i + 1 & ")")
adrsc.MoveNext
Loop
End If
adrsb.MoveNext
Loop
End If
Loop While adrsb.RecordCount <> 0
Debug.Print "finished"
End Function
I'm learning VBscript to assist creating user forms in outlook. With this appointment form I'm attempting to create a pre-formatted email signed off with the name of the current user. I only want the output to be the current users first name. It is currently returning the full name.
How can I split the user name or get only the users first name?
Thanks in advance.
Sub commandbutton1_click()
Set MyApp = CreateObject("Outlook.Application")
Set MyItem = MyApp.CreateItem(0) 'olMailItem
set prop = item.userproperties.find("Mobile")
set currentuser = application.getNameSpace("MAPI").CurrentUser
Set prop1 = item.userProperties.find("Subject")
Set prop2 = item.userProperties.find("Location")
Set prop3 = item.userProperties.find("DateStart")
dteThen = dateAdd("h", -1, Now())
With MyItem
.To = prop & "#etxt.co.nz"
.Subject = ""
.Body = "Hi " & Subject & vbCrlf & vbCrlf & "This is a reminder about your meeting at " & Location & vbCrlf & vbCrlf & "Thanks" & currentUser
.DeferredDeliveryTime = DateStart + dteThen
End With
MyItem.Display
end sub
Fairly simple...
Sub commandbutton1_click()
Set MyApp = CreateObject("Outlook.Application")
Set MyItem = MyApp.CreateItem(0) 'olMailItem
set prop = item.userproperties.find("Mobile")
set currentuser = application.getNameSpace("MAPI").CurrentUser
Set prop1 = item.userProperties.find("Subject")
Set prop2 = item.userProperties.find("Location")
Set prop3 = item.userProperties.find("DateStart")
arrUserName = Split(currentUser, ",") 'Split the name using ","
strName = Trim(arrUserName(1)) 'Remove any space
dteThen = dateAdd("h", -1, Now())
With MyItem
.To = prop & "#etxt.co.nz"
.Subject = ""
.Body = "Hi " & Subject & vbCrlf & vbCrlf & "This is a reminder about your meeting at " & Location & vbCrlf & vbCrlf & "Thanks," & vbcrLF & strName 'use of strName
.DeferredDeliveryTime = DateStart + dteThen
End With
MyItem.Display
end sub
I have set this up to auto email through the Outlook client, is it possible to change this code to work directly through an SMTP server? And could anyone possibly help me do it?
Any help would be much appreciated, thanks!
Set app = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In fso.GetFolder("Y:\Billing_Common\autoemail").Files
If LCase(fso.GetExtensionName(f)) = "xls" Then
Set wb = app.Workbooks.Open(f.Path)
set sh = wb.Sheets("Auto Email Script")
row = 2
name = "Customer"
email = sh.Range("A" & row)
subject = "Billing"
the = "the"
LastRow = sh.UsedRange.Rows.Count
For r = row to LastRow
If App.WorkSheetFunction.CountA(sh.Rows(r)) <> 0 Then
SendMessage email, name, subject, TRUE, _
NULL, "Y:\Billing_Common\autoemail\Script\energia-logo.gif", 143,393
row = row + 1
email = sh.Range("A" & row)
End if
Next
wb.Close
End If
Next
Sub SendMessage(EmailAddress, DisplayName, Subject, DisplayMsg, AttachmentPath, ImagePath, ImageHeight, ImageWidth)
' Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
template = FindTemplate()
' Create the message.
Set objOutlookMsg = objOutlook.CreateItem(0)
With objOutlookMsg
' Add the To recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add(EmailAddress)
objOutlookRecip.resolve
objOutlookRecip.Type = 1
' Set the Subject, Body, and Importance of the message.
.Subject = Subject
.bodyformat = 3
.Importance = 2 'High importance
body = Replace(template, "{First}", name)
body = Replace(body, "{the}", the)
if not isNull(ImagePath) then
if not ImagePath = "" then
.Attachments.add ImagePath
image = split(ImagePath,"\")(ubound(split(ImagePath,"\")))
body = Replace(body, "{image}", "<img src='cid:" & image & _
"'" & " height=" & ImageHeight &" width=" & ImageWidth & ">")
end if
else
body = Replace(body, "{image}", "")
end if
if not isNull(AttachMentPath) then
.Attachments.add AttachmentPath
end if
.HTMLBody = body
.Save
.Send
End With
Set objOutlook = Nothing
End Sub
Function FindTemplate()
Set OL = GetObject("", "Outlook.Application")
set Drafts = OL.GetNamespace("MAPI").GetDefaultFolder(16)
Set oItems = Drafts.Items
For Each Draft In oItems
If Draft.subject = "Template" Then
FindTemplate = Draft.HTMLBody
Exit Function
End If
Next
End Function
If you want to send mail directly to an SMTP server, there's no need to go through Outlook in the first place. Just use CDO. Something like this:
schema = "http://schemas.microsoft.com/cdo/configuration/"
Set msg = CreateObject("CDO.Message")
msg.Subject = "Test"
msg.From = "sender#example.com"
msg.To = "recipient#example.org"
msg.TextBody = "This is some sample message text."
With msg.Configuration.Fields
.Item(schema & "sendusing") = 2
.Item(schema & "smtpserver") = "smtp.intern.example.com"
.Item(schema & "smtpserverport") = 25
.Update
End With
msg.Send