rivate Sub CmdOpenCmtList_Click()
On Error GoTo SubError
Dim xlApp As Excel.Application
Dim xlWkb As Excel.Workbook
Dim xlWks As Excel.Worksheet
Dim i As Integer 'First Row: CmtAwd
Dim j As Integer 'First Row: CmtJaws
Dim k As Integer 'First Row: CmtSick
Dim l As Integer 'Second Row: CmtCust
Dim m As Integer 'Second Row: CmtJun
Dim n As Integer 'Second Row: CmtMain
Dim SQLCmtAwd As String
'Dim SQLCmtAwdChair As String 'no chairman
Dim SQLCmtJaws As String
Dim SQLCmtJawsChair As String
Dim SQLCmtSick As String
Dim SQLCmtSickChair As String
Dim SQLCmtCust As String
Dim SQLCmtCustChair As String
Dim SQLCmtJun As String
Dim SQLCmtJunChair As String
Dim SQLCmtMain As String
Dim SQLCmtMainChair As String
Dim rsCmtAwd As DAO.Recordset
'Dim rsCmtAwdChair As DAO.Recordset 'no chairmen
Dim rsCmtJaws As DAO.Recordset
Dim rsCmtJawsChair As DAO.Recordset
Dim rsCmtSick As DAO.Recordset
Dim rsCmtSickChair As DAO.Recordset
Dim rsCmtCust As DAO.Recordset
Dim rsCmtCustChair As DAO.Recordset
Dim rsCmtJun As DAO.Recordset
Dim rsCmtJunChair As DAO.Recordset
Dim rsCmtMain As DAO.Recordset
Dim rsCmtMainChair As DAO.Recordset
SQLCmtAwd = "SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtAwd, TblMembers.CmtAwd " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtAwd)=True))"
'SQLCmtAwdChair = " SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtAwdChair, [FullName] & "" - Chairman"" AS FullNameChair " & _
' " FROM TblMembers " & _
' " WHERE (((TblMembers.CmtAwdChair)=True))"
SQLCmtJaws = "SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtJaws " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtJaws)=True))"
SQLCmtJawsChair = " SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtJawsChair, [FullName] & "" - Chairman"" AS FullNameChair " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtJawsChair)=True))"
SQLCmtSickChair = " SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtSickChair, [FullName] & "" - Chairman"" AS FullNameChair " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtSickChair)=True))"
SQLCmtSick = "SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtSickChair " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtSick)=True))"
SQLCmtCustChair = " SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtCustChair, [FullName] & "" - Chairman"" AS FullNameChair " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtCustChair)=True))"
SQLCmtCust = "SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtCust " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtCust)=True))"
SQLCmtJunChair = " SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtJunChair, [FullName] & "" - Chairman"" AS FullNameChair " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtJunChair)=True))"
SQLCmtJun = "SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtJun " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtJun)=True))"
SQLCmtMainChair = " SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtMainChair, [FullName] & "" - Chairman"" AS FullNameChair " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtMainChair)=True))"
SQLCmtMain = "SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.CmtMainChair " & _
" FROM TblMembers " & _
" WHERE (((TblMembers.CmtMain)=True))"
Set rsCmtAwd = CurrentDb.OpenRecordset(SQLCmtAwd, dbOpenSnapshot)
'Set rsCmtAwdChair = CurrentDb.OpenRecordset(SQLCmtAwdChair, dbOpenSnapshot)
Set rsCmtJaws = CurrentDb.OpenRecordset(SQLCmtJaws, dbOpenSnapshot)
Set rsCmtJawsChair = CurrentDb.OpenRecordset(SQLCmtJawsChair, dbOpenSnapshot)
Set rsCmtSick = CurrentDb.OpenRecordset(SQLCmtSick, dbOpenSnapshot)
Set rsCmtSickChair = CurrentDb.OpenRecordset(SQLCmtSickChair, dbOpenSnapshot)
Set rsCmtCust = CurrentDb.OpenRecordset(SQLCmtCust, dbOpenSnapshot)
Set rsCmtCustChair = CurrentDb.OpenRecordset(SQLCmtCustChair, dbOpenSnapshot)
Set rsCmtJun = CurrentDb.OpenRecordset(SQLCmtJun, dbOpenSnapshot)
Set rsCmtJunChair = CurrentDb.OpenRecordset(SQLCmtJunChair, dbOpenSnapshot)
Set rsCmtMain = CurrentDb.OpenRecordset(SQLCmtMain, dbOpenSnapshot)
Set rsCmtMainChair = CurrentDb.OpenRecordset(SQLCmtMainChair, dbOpenSnapshot)
Set xlApp = New Excel.Application
Set xlWkb = xlApp.Workbooks.Open(CurrentProject.Path & "\Master\CommitteeList.xlsx")
Set xlWks = xlWkb.Sheets("Sheet1")
xlApp.Visible = True
i = 10 'First Row: CmtAwd
j = 10 'First Row: CmtJaws
k = 10 'First Row: CmtSick
With xlWks
Do While Not rsCmtAwdChair.EOF
.Range("E9").Value = (rsCmtAwdChair!FullNameChair)
rsCmtAwdChair.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtAwd.EOF
.Range("E" & i - 1).Value = Nz(rsCmtAwd!FullName, "")
i = i + 1
rsCmtAwd.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtJawsChair.EOF
.Range("Y9").Value = (rsCmtJawsChair!FullNameChair)
rsCmtJawsChair.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtJaws.EOF
.Range("Y" & j).Value = Nz(rsCmtJaws!FullName, "")
j = j + 1
rsCmtJaws.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtSickChair.EOF
.Range("AS9").Value = (rsCmtSickChair!FullNameChair)
rsCmtSickChair.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtSick.EOF
.Range("AS" & k).Value = Nz(rsCmtSick!FullName, "")
k = k + 1
rsCmtSick.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtCustChair.EOF
.Range("E16").Value = (rsCmtCustChair!FullNameChair)
rsCmtCustChair.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtCust.EOF
.Range("AS" & i).Value = Nz(rsCmtCust!FullName, "")
i = i + 17
rsCmtSick.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtJunChair.EOF
.Range("Y16").Value = (rsCmtJunChair!FullNameChair)
rsCmtJunChair.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtJun.EOF
.Range("Y" & m).Value = Nz(rsCmtJun!FullName, "")
m = m + 1
rsCmtSick.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtMainChair.EOF
.Range("AS16").Value = (rsCmtMainChair!FullNameChair)
rsCmtMainChair.MoveNext
Loop
End With
With xlWks
Do While Not rsCmtMain.EOF
.Range("Y" & n).Value = Nz(rsCmtMain!FullName, "")
n = n + 1
rsCmtMain.MoveNext
Loop
End With
SubExit:
On Error Resume Next
rsCmtAwd.Close
'rsCmtAwdChair.Close
rsCmtJaws.Close
rsCmtJawsChair.Close
rsCmtSick.Close
rsCmtSickChair.Close
rsCmtCust.Close
rsCmtCustChair.Close
rsCmtJun.Close
rsCmtJunChair.Close
rsCmtMain.Close
rsCmtMainChair.Close
Set rsCmtAwd = Nothing
'Set rsCmtAwdChair = Nothing
Set rsCmtJaws = Nothing
Set rsCmtJawsChair = Nothing
Set rsCmtSick = Nothing
Set rsCmtSickChair = Nothing
Set rsCustAwd = Nothing
Set rsCmtCustChair = Nothing
Set rsCmtJun = Nothing
Set rsCmtJunChair = Nothing
Set rsCmtMain = Nothing
Set rsCmtSickMain = Nothing
Exit Sub
SubError:
MsgBox "Error Number: " & Err.Number & "=" & Err.Description, vbCritical + vbOKOnly, "An error occured"
GoTo SubExit
End Sub
Is there a better way to do this. I solved my previous problem, but now I get an error of 424 object required. Before the object error I was getting no record error, I checked the queries all return records.
Is there a better way to loop thru rs and get the output to the excel file, I have about 18 committes that need to have a chairman and 1-5 members. Cells on excel ie... Y16 for Chairman and then in y17 the list of members.
1-
Instead of looping, you can use 'CopyfromRecordSet'. You just need to select the starting cell on each sheet of your Excel file, and the system do the rest.
I give you the Microsoft link:https://msdn.microsoft.com/en-us/library/office/aa223845(v=office.11).aspx
2-
On the 424 Object required problem, did you try to debug the code to find out which line the error occurs?
Hope this can help!
Related
Here is my updated code per #Parfait suggestion. It still isn't working, getting the following error:
Run-time error '3421'
Data type conversion error
On the following line: Set rec = qdef.OpenRecordset(strQry)
Option Compare Database
Private Sub Command0_Click()
Dim db As DAO.Database
Dim qdef As DAO.QueryDef
Dim rec As DAO.Recordset
Dim olApp As Object
Dim olItem As Variant
Dim strQry As String
Dim aHead(1 To 4) As String
Dim aRow(1 To 4) As String
Dim aBody() As String
Dim lCnt As Long
'Prepared Statement No Data
strQry = "PARAMETERS cboParam TEXT(255);" _
& " SELECT [Loan ID], [Prior Loan ID], [SRP Rate], [SRP Amount] " _
& " FROM emailtable " _
& " WHERE [Seller Name:Refer to As] = [cboParam]"
Set db = CurrentDb
Set qdef = db.CreateQueryDef("", strQry)
' BIND PARAMETER
qdef!cboParam = Me.Combo296
' OPEN RECORDSET
Set rec = qdef.OpenRecordset(strQry)
'Create the header row
aHead(1) = "Loan ID"
aHead(2) = "Prior Loan ID"
aHead(3) = "SRP Rate"
aHead(4) = "SRP Amount"
lCnt = 1
ReDim aBody(1 To lCnt)
aBody(lCnt) = "<HTML><body><table border='2'><tr><th>" & Join(aHead, "</th><th>") & "</th></tr>"
If Not (rec.BOF And rec.EOF) Then
Do While Not rec.EOF
lCnt = lCnt + 1
ReDim Preserve aBody(1 To lCnt)
aRow(1) = rec("[Loan ID]")
aRow(2) = rec("[Prior Loan ID]")
aRow(3) = rec("[SRP Rate]")
aRow(4) = rec("[SRP Amount]")
aBody(lCnt) = "<tr><td>" & Join(aRow, "</td><td>") & "</td></tr>"
rec.MoveNext
Loop
End If
aBody(lCnt) = aBody(lCnt) & "</table></body></html>"
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
With objMail
.Display 'To display message
.To = Me.Combo88
.cc = Me.Combo282
.Subject = "*SECURE* " & Me.Combo296 & " Refund Request (" & Me.Combo212 & " " & Me.Combo284 & ")"
.HTMLBody = "<p><font face=""calibri"" style=""font-size:11pt;"">Greetings,</p>" _
& "<p>We recently acquired loans from " & Me.Combo296 & ", some of which have paid in full and meet the criteria for early prepayment defined in the governing documents. We are requesting a refund of the SRP amount detailed on the attached list.</p>" _
& "<p>Please wire funds to the following instructions:</p>" _
& "<ul>Bank Name: My Bank</ul>" _
& "<ul>ABA: 1111111</ul>" _
& "<ul>Credit To: ABC Mortgage</ul>" _
& "<ul>Acct: 11111111111</ul>" _
& "<ul>Description: " & Combo296 & " EPO SRP Refund</ul>" _
& "<p>Thank you for the opportunity to service loans from " & Me.Combo296 & "! We appreciate your partnership.</p>" _
& "<p>If you have any questions, please contact your Relationship Manager, " & Me.Combo336 & " (Cc'd).</p>" _
& "<p><br>Sincerely,</br>" _
& "<br>Acquisitions</br>" _
& "<br>acquisitions#us.com</br></p>"
End With
rec.Close
Set rec = Nothing: Set qdef = Nothing: Set db = Nothing
End Sub
Any help would be greatly appreciated.
Avoid concatenating VBA data to SQL even HTML strings. Instead, consider the industry standard of SQL parameterization.
Dim db DAO.Database, qdef As DAO.QueryDef, rec AS DAO.Recordset
' PREPARED STATEMENT (NO DATA)
strQry = "PARAMETERS cboParam TEXT(255);" _
& " SELECT [Loan ID], [Prior Loan ID], [SRP Rate], [SRP Amount] " _
& " FROM emailtable " _
& " WHERE [Seller Name:Refer to As] = [cboParam]"
Set db = CurrentDb
Set qdef = db.CreateQueryDef("", strQry)
' BIND PARAMETER
qdef!cboParam = Me.Combo296
' OPEN RECORDSET
Set rec = qdef.OpenRecordset()
... ' REST OF CODE USING rec
rec.Close
Set rec = Nothing: Set qdef = Nothing: Set db = Nothing
Also, consider saving the email message HTML markup as a text in the table or as text box on form with placeholders to be replaced with combo box values:
.HTMLBody = Replace(Replace(Me.EmailMessage, "placeholder1", Me.Combo296),
"placeholder2", Me.Combo336)
I'm guessing (from your photo) that the data type of your [Seller Name:Refer to as] column is supposed to be string? In which case, your query is missing quotes to denote the string value in your comparison:
'Create each body row
strQry = "Select * from emailtable where [Seller Name:Refer to As] = """ & Me.Combo296 & """"
Set db = CurrentDb
Set rec = CurrentDb.OpenRecordset(strQry)
We are trying to store new mail item components into excel and assign tkt id, have tried doing it with single shared mailbox and succeeded but we want to implement same for 20 shared mail boxes. how can outlook vba event/trigger identify as soon as new email arrives to one of the 20 shared mail boxes.
this is code which will only work for default inbox:
Private Sub inboxItems_ItemAdd(ByVal Item As Object)
Dim Msg As Outlook.MailItem
Dim MessageInfo
Dim Result
If TypeName(Item) = "MailItem" Then
Dim cn As Object
Dim sCon As String
Dim sSQL As String
Dim bytHasAttachment As String
Dim strAddress As String
Dim objSender, exUser
Dim olRecipient As Outlook.Recipient
Dim strToEmails, strCcEmails, strBCcEmails As String
For Each olRecipient In Item.Recipients
Dim mail As String
If olRecipient.AddressEntry Is Nothing Then
mail = olRecipient.Address
ElseIf olRecipient.AddressEntry.GetExchangeUser Is Nothing Then
mail = olRecipient.Address
Else
mail = olRecipient.AddressEntry.GetExchangeUser.PrimarySmtpAddress
End If
If olRecipient.Type = Outlook.OlMailRecipientType.olTo Then
strToEmails = strToEmails + mail & ";"
ElseIf olRecipient.Type = Outlook.OlMailRecipientType.olCC Then
strCcEmails = strCcEmails + mail & ";"
ElseIf olRecipient.Type = Outlook.OlMailRecipientType.olBCC Then
strBCcEmails = strBCcEmails + mail & ";"
End If
Next
With Item
If Item.Attachments.Count > 0 Then
bytHasAttachment = 1
Else
bytHasAttachment = 0
End If
End With
'On Error Resume Next 'PropertyAccessor can raise an exception if a property is not found
If Item.SenderEmailType = "SMTP" Then
strAddress = Item.SenderEmailAddress
Else
'read PidTagSenderSmtpAddress
strAddress = Item.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x5D01001F")
If Len(strAddress) = 0 Then
Set objSender = Item.Sender
If Not (objSender Is Nothing) Then
'read PR_SMTP_ADDRESS_W
strAddress = objSender.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x39FE001F")
If Len(strAddress) = 0 Then
Set exUser = objSender.GetExchangeUser
If Not (exUser Is Nothing) Then
strAddress = exUser.PrimarySmtpAddress
End If
End If
End If
End If
End If
On Error GoTo ErrorHandler
Set cn = CreateObject("ADODB.Connection")
sCon = "Driver=MySQL ODBC 8.0 ANSI Driver;SERVER=localhost;UID=root;PWD={Platinum#123};DATABASE=liva_dev_gm;PORT=3306;COLUMN_SIZE_S32=1;DFLT_BIGINT_BIND_STR=1"
cn.Open sCon
sSQL = "INSERT INTO tbl_gmna_emailmaster_inbox (eMail_Icon, eMail_MessageID, eMail_Folder, eMail_Act_Subject, eMail_From, eMail_TO, eMail_CC, " & _
"eMail_BCC, eMail_Body, eMail_DateReceived, eMail_TimeReceived, eMail_Anti_Post_Meridiem, eMail_Importance, eMail_HasAttachment) " & _
"VALUES (""" & Item.MessageClass & """, " & _
"""" & Item.EntryID & """, " & _
"""Inbox""" & ", " & _
"""" & Item.Subject & """, " & _
"""" & strAddress & """, " & _
"""" & strToEmails & """, " & _
"""" & strCcEmails & """, " & _
"""" & strBCcEmails & """, " & _
"""" & Item.Body & """, " & "'" & Format(Item.ReceivedTime, "YYYY-MM-DD") & "', " & "'" & Format(Item.ReceivedTime, "hh:mm:ss") & "', " & "'" & Format(Item.ReceivedTime, "am/pm") & "', " & "'" & Item.Importance & "', " & "'" & bytHasAttachment & "')"
cn.Execute sSQL
End If
ExitNewItem:
bytHasAttachment = ""
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ExitNewItem
End Sub
If the 20 shared mailboxes are in the navigation pane.
Option Explicit
Private WithEvents inboxItms As Items
Private WithEvents sharedInboxItms1 As Items
' ...
Private WithEvents sharedInboxItms20 As Items
Private Sub Application_Startup()
Dim defaultInbox As Folder
Dim sharedMailbox1 As Folder
Dim sharedInbox1 As Folder
' ...
Dim sharedMailbox20 As Folder
Dim sharedInbox20 As Folder
Set defaultInbox = Session.GetDefaultFolder(olFolderInbox)
Set inboxItms = defaultInbox.Items
Set sharedMailbox1 = Session.Folders("SharedMailbox1#somewhere.com")
Set sharedInbox1 = sharedMailbox1.Folders("Inbox")
' typo fixed
'Set sharedInboxItms1 = sharedInbox1.Folders("Inbox").Items
Set sharedInboxItms1 = sharedInbox1.Items
' ...
Set sharedMailbox20 = Session.Folders("SharedMailbox20#somewhere.com")
Set sharedInbox20 = sharedMailbox20.Folders("Inbox")
' typo fixed
'Set sharedInboxItms20 = sharedInbox20.Folders("Inbox").Items
Set sharedInboxItms20 = sharedInbox20.Items
End Sub
Private Sub inboxItms_ItemAdd(ByVal Item As Object)
' current code for default inbox
End Sub
Private Sub sharedInboxItms1_ItemAdd(ByVal Item As Object)
inboxItms_ItemAdd Item
End Sub
' ...
Private Sub sharedInboxItms20_ItemAdd(ByVal Item As Object)
inboxItms_ItemAdd Item
End Sub
This query is used to call a specific set of work requests over a period of time, this query takes date inputs and the system number from a form. The query result is then put into another form to view.
I've gone over all VBA code that is relevant to this and there seems to be no problems there however so I have determined that the query is too complex and as I am not too well versed in SQL I am not too sure where to go from here.
This Query also provides a #name? Error viewed in forms
The Query
SELECT tbl_NIMSD_dbo_TIDWRREQ.WO_REQ_NUMBER
,tbl_NIMSD_dbo_TIDWRREQ.WR_TASK_TITLE
,"Click Here" AS [Work Request Description]
,tbl_NIMSD_dbo_TIDWRREQ.SYSTEM_CODE
,tbl_NIMSD_dbo_TIDWRREQ.UNIT
,[tbl_NIMSD_dbo_TIDWRREQ].[Unit] + "-" + [tbl_NIMSD_dbo_TIDWRREQ].[SYSTEM_CODE] + "-" + [tbl_NIMSD_dbo_TIDWRREQ].[EQUIPMENT_NUMBER] AS EQ_TAG
,tbl_NIMSD_dbo_TIDWRREQ.WO_REQ_STATUS
,CDate(Format([WO_REQ_DATE_ENTER], "####\/##\/##")) AS WR_CREATION_DATE
FROM qryfrmOutput
INNER JOIN tbl_NIMSD_dbo_TIDWRREQ ON qryfrmOutput.SCI = tbl_NIMSD_dbo_TIDWRREQ.SYSTEM_CODE
WHERE (
((tbl_NIMSD_dbo_TIDWRREQ.SYSTEM_CODE) = Forms ! frmOutputDarlington ! ListSelectedSystem)
AND (
(CDate(Format([WO_REQ_DATE_ENTER], "####\/##\/##"))) >= Forms ! frmOutputDarlington ! TextStartDate
AND (CDate(Format([WO_REQ_DATE_ENTER], "####\/##\/##"))) <= (Forms ! frmOutputDarlington ! TextEndDate + 1)
)
);
The function that inserts the system code and date,
strSCI = ConcatRelated("[SCI]", "[tblSystemAssignmentList]", "[Facility] = '" & [TempVars]![varFacility] & "' AND [Selected] = True", , " OR ", "(tbl_NIMSD_dbo_TIDWRREQ.SYSTEM_CODE)='")
searchString = "(tbl_NIMSD_dbo_TIDWRREQ.SYSTEM_CODE)=Forms!frmOutputDarlington!ListSelectedSystem"
If InStr(1, SCIList, searchString) <> 0 Then
SCIList = Replace(SCIList, "(tbl_NIMSD_dbo_TIDWRREQ.SYSTEM_CODE)=Forms!frmOutputDarlington!ListSelectedSystem", strSCI)
Else
SCIList = Replace(SCIList, "(tbl_NIMSD_dbo_TIDWRREQ.SYSTEM_CODE)=[Forms]![frmOutputDarlington]![ListSelectedSystem]", strSCI)
End If
ConcatRelated
Dim rs As DAO.Recordset
Dim rsMV As DAO.Recordset
Dim strSQL As String
Dim strOut As String
Dim lngLen As Long
Dim bIsMultiValue As Boolean
ConcatRelated = Null
strSQL = "SELECT " & strField & " FROM " & strTable
If strWhere <> vbNullString Then
strSQL = strSQL & " WHERE " & strWhere
End If
If strOrderBy <> vbNullString Then
strSQL = strSQL & " ORDER BY " & strOrderBy
End If
Set rs = DBEngine(0)(0).OpenRecordset(strSQL, dbOpenDynaset)
bIsMultiValue = (rs(0).Type > 100)
Do While Not rs.EOF
If bIsMultiValue Then
Set rsMV = rs(0).Value
Do While Not rsMV.EOF
If Not IsNull(rsMV(0)) Then
strOut = strOut & rsMV(0) & strSeparator
End If
rsMV.MoveNext
Loop
Set rsMV = Nothing
ElseIf Not IsNull(rs(0)) And strFieldName = "(tblImportedSCRs.System) Like '*" Then
strOut = strOut & strFieldName & rs(0) & "*'" & strSeparator
ElseIf Not IsNull(rs(0)) Then
strOut = strOut & strFieldName & rs(0) & "'" & strSeparator
End If
rs.MoveNext
Loop
rs.Close
lngLen = Len(strOut) - Len(strSeparator)
If lngLen > 0 Then
ConcatRelated = Left(strOut, lngLen)
End If
exit_handler:
Set rsMV = Nothing
Set rs = Nothing
Exit Function
Err_Handler:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation, "ConcatRelated()"
Resume exit_handler
End Function
When I run the code it should output the requested reports within the requested timeframe, however instead of the actual values it displays #name?
For a start, reduce the code and specify the parameters:
PARAMETERS
Forms!frmOutputDarlington!ListSelectedSystem Long,
Forms!frmOutputDarlington!TextStartDate DateTime,
Forms!frmOutputDarlington!TextEndDate DateTime;
SELECT
tbl_NIMSD_dbo_TIDWRREQ.WO_REQ_NUMBER,
tbl_NIMSD_dbo_TIDWRREQ.WR_TASK_TITLE,
"Click Here" AS [Work Request Description],
tbl_NIMSD_dbo_TIDWRREQ.SYSTEM_CODE,
tbl_NIMSD_dbo_TIDWRREQ.UNIT,
[tbl_NIMSD_dbo_TIDWRREQ].[Unit] & "-" & [tbl_NIMSD_dbo_TIDWRREQ].[SYSTEM_CODE] & "-" & [tbl_NIMSD_dbo_TIDWRREQ].[EQUIPMENT_NUMBER] AS EQ_TAG,
tbl_NIMSD_dbo_TIDWRREQ.WO_REQ_STATUS,
DateValue([WO_REQ_DATE_ENTER]) AS WR_CREATION_DATE
FROM
qryfrmOutput
INNER JOIN
tbl_NIMSD_dbo_TIDWRREQ ON
qryfrmOutput.SCI = tbl_NIMSD_dbo_TIDWRREQ.SYSTEM_CODE
WHERE
tbl_NIMSD_dbo_TIDWRREQ.SYSTEM_CODE = Forms!frmOutputDarlington!ListSelectedSystem
AND
DateValue([WO_REQ_DATE_ENTER]) >= Forms!frmOutputDarlington!TextStartDate
AND
DateValue([WO_REQ_DATE_ENTER]) <= DateAdd("d", 1, Forms!frmOutputDarlington!TextEndDate)
I am trying to figure out what wrong may be with a function in Excel that tries to join two tables. I presume the error is somewhere in SQL string.
The function works well without a join, returning correctly a table to an array - range of cells. ie when strSQL is only "SELECT * FROM [" & currAddress & "] "
It does not work when the string contains a join, ie strSQL = "SELECT * FROM [" & currAddress & "] " & _
"LEFT JOIN [" & currAddress2 & "] ON [Indeks].[" & currAddress & "] = [Indeks2].[" & currAddress2 & "];"
Here is my code, thank you for help:
Function SQL(dataRange As Range, dataRange2 As Range) As Variant
Application.Volatile
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim currAddress, currAddress2 As String
Dim varHdr, varDat, contentOut As Variant
Dim nc, nr, i, j As Long
SQL = Null
currAddress = ActiveSheet.Name & "$" & dataRange.Address(False, False)
Debug.Print currAddress
currAddress2 = ActiveSheet.Name & "$" & dataRange2.Address(False, False)
Debug.Print currAddress2
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=0"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
rs.CursorLocation = adUseClient ' required to return the number of rows correctly
cn.Open strCon
strSQL = "SELECT * FROM [" & currAddress & "] " & _
"LEFT JOIN [" & currAddress2 & "] ON [Indeks].[" & currAddress & "] = [Indeks2].[" & currAddress2 & "];"
Debug.Print strSQL
rs.Open strSQL, cn
'Check if recordset is empty
If rs.EOF Then
MsgBox "Function does not return any values"
SQL = ""
Exit Function
End If
' Process Column Headings
nc = rs.Fields.Count
ReDim varHdr(nc - 1, 0)
For i = 0 To rs.Fields.Count - 1
varHdr(i, 0) = rs.Fields(i).Name
Next
' Get Rows from the Recordset
nr = rs.RecordCount
varDat = rs.GetRows
' Combing Header and Data and Transpose
ReDim contentOut(0 To nr, 0 To nc - 1)
For i = 0 To nc - 1
contentOut(0, i) = varHdr(i, 0)
Next
For i = 1 To nr
For j = 0 To nc - 1
contentOut(i, j) = varDat(j, i - 1)
Next
Next
' Optional solution: Write Output Array to Sheet2
' With Sheet2
' .Cells.Clear
' .Range("A1").Resize(nr, nc) = contentOut
' End With
'Figure out size of calling range which will receive the output array
Dim nRow As Long: nRow = Application.Caller.Rows.Count
Dim nCol As Long: nCol = Application.Caller.Columns.Count
'Error if calling range too small
If nRow < UBound(contentOut, 1) Or nCol < UBound(contentOut, 2) Then
'Popup message
'MsgBox "your range is too small."
' or return #VALUE! error
SQL = "Too small range" 'CVErr(xlValue)
' or both or whatever else you want there to happen
Exit Function
End If
'Initialise output array to match size of calling range
Dim varOut As Variant
ReDim varOut(1 To nRow, 1 To nCol)
'And fill it with some background value
Dim iRow As Long
Dim iCol As Long
For iRow = 1 To nRow
For iCol = 1 To nCol
varOut(iRow, iCol) = "" ' or "funny bear", or whatever
Next
Next
'Put content in output array and return
For iRow = 0 To UBound(contentOut, 1)
For iCol = 0 To UBound(contentOut, 2)
varOut(iRow + 1, iCol + 1) = contentOut(iRow, iCol)
Next
Next
SQL = varOut
'Cleanup
Erase contentOut
Erase varHdr
Erase varDat
rs.Close
Set rs = Nothing
Set cn = Nothing
End Function
It looks like you are not specifying the fields/columns in the join. Both currAddress and curAddress2 look like tables. The SQL should be something like:
strSQL = "SELECT * FROM [Table1] " & _
"LEFT JOIN [Table2] ON [Table1].[Field] = [Table2].[Field];"
Are Indeks and Indeks2 your field names? If so, you need to place the field name after the table name:
strSQL = "SELECT * FROM [" & currAddress & "] " & _
"LEFT JOIN [" & currAddress2 & "] ON [" & currAddress & "].[Indeks] = [" & currAddress2 & "].[Indeks2];"
I believe 'Indeks' is your common field in the two tables, then strSQL should be this:
strSQL = "SELECT * FROM [" & currAddress & "] " & _
"LEFT JOIN [" & currAddress2 & "] ON [" & currAddress & "].[Indeks] = [" & currAddress2 & "].[Indeks]"
I have designed a macro which should extract from a workbook database all employees who were hired between 2 Dates.
Unfortunatley I'm getting a error mesage when I run the query.
Error:
Data Type mismatch in criteria expression.
I don't know how to fix the issue.
My regional settings:
Short date: dd.MM.yyyy
Long date: dddd, d.MMMM.yyyy
First day of week: Monday
Here the code:
Public Sub HIREDATE()
Application.ScreenUpdating = False
Dim cnStr As String
Dim rs As ADODB.Recordset
Dim query As String
Dim fileName As String
Dim pom1 As String
Dim x As String, w, e, blad As String, opis As String
Set w = Application.FileDialog(msoFileDialogFilePicker)
With w
.AllowMultiSelect = False
If .Show = -1 Then
fileName = w.SelectedItems(1)
Else
Exit Sub
End If
End With
cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & fileName & ";" & _
"Extended Properties=Excel 12.0"
On Error GoTo Anuluj
x = InputBox("Wprowadz dwie daty od do oddzielając je przecinkiem -- Przykład 01.01.2015,01.05.2015")
strg = ""
k = Split(x, ",")
e = Application.CountA(k)
For m = LBound(k) To UBound(k)
If e = 1 Then
strg = strg & " [DEU1$].[Last Start Date] = '" & k(m) & "';"
Exit For
ElseIf e = 2 And e Mod 2 = 0 Then
strg = " [DEU1$].[Last Start Date] BETWEEN '" & CDate(k(m)) & "' AND '" & CDate(k(m + 1)) & "';"
Exit For
End If
Next m
On Error GoTo opiszblad
Set rs = New ADODB.Recordset
query = "SELECT [Emplid], [First Name]+ ' ' +[Last Name] From [DEU1$] WHERE" & strg
rs.Open query, cnStr, adOpenUnspecified, adLockUnspecified
Cells.Clear
Dim cell As Range, i As Long
With Range("A3").CurrentRegion
.Select
For i = 0 To rs.Fields.Count - 1
.Cells(1, i + 1).Value = rs.Fields(i).Name
Next i
Range("A4").CopyFromRecordset rs
.Cells.Select
.EntireColumn.AutoFit
End With
rs.Close
Application.ScreenUpdating = True
Exit Sub
Anuluj:
Exit Sub
opiszblad:
e = Err.Number
blad = Err.Source
opis = Err.Description
opisbledu = MsgBox(e & " " & blad & " " & opis, vbInformation, "Błąd")
Exit Sub
End Sub
You need properly formatted string expressions for your dates and to validate the user input:
If e = 1 And IsDate(k(m)) Then
strg = strg & " [DEU1$].[Last Start Date] = #" & Format(DateValue(k(m)), "yyyy\/mm\/dd") & "#;"
Exit For
ElseIf e = 2 And e Mod 2 = 0 And IsDate(k(m + 1)) Then
strg = " [DEU1$].[Last Start Date] BETWEEN #" & Format(DateValue(k(m)), "yyyy\/mm\/dd") & "# AND #" & Format(DateValue(k(m + 1)), "yyyy\/mm\/dd") & "#;"
Exit For
End If