How do I assign a sharepoint 2013 task to someone in VBA - vba

Here is my code, I'm in using VBA. I get no errors, the task is added to the sharepoint list, but the Assigned To field is blank.
I have also listed all the fields in the recordset and there is no Assignment field available. I noticed some unanswered questions on the web about how to query the value of a lookup field.
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=0;RetrieveIds=Yes;" & _
"DATABASE=" & sSHAREPOINT_SITE & ";" & _
"LIST=" & sTASK_LIST_GUID & ";"
' Create some new objects.
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection.
With cn
.ConnectionString = sConn
.Open
End With
sSQL = "SELECT * FROM [Tasks] as tbl;"
' Open up the recordset.
rs.Open sSQL, cn, adOpenStatic, adLockOptimistic
With rs
.AddNew
![Task Name] = "test"
AssignedTo = "SomeEmailAddress"
![Categories] = "Data Requests"
.Update
End With
rs.Close
I do know how to do this if I "connect with Outlook", but I was trying to avoid all that.

The value would have to be in the format of LookupId;#LookupValue
Where LookupId is the user's ID for that particular site and the LookupValue is the users Display Name
So you would have:
AssignedTo = "48;#Chris McKay"

Related

REPLACE data in Access table

I use VBA Word with Access, to create/store medical visit notes for Nursing homes.
The following is an example of how I get data out of Access (obviously picking up mid-Sub). This is populating a ComboBox in Word which gives me a list of all my patients, it is working great!
'....
Set Conn = New ADODB.Connection
Set rs = New ADODB.Recordset
strConn = ActiveDocument.CustomDocumentProperties("strConn").Value
Conn.Open (strConn)
qry = "SELECT * FROM tblPatientInfo ORDER BY LastName, Firstname"
rs.Open qry, Conn, adOpenKeyset
rs.MoveFirst
x = 0
While Not rs.EOF
F1.ComboDashPtList.AddItem
F1.ComboDashPtList.List(x, 0) = rs.Fields("LastName").Value & ""
F1.ComboDashPtList.List(x, 1) = rs.Fields("FirstName").Value & ""
F1.ComboDashPtList.List(x, 2) = Format(rs.Fields("DOB").Value, "MM\/dd\/yyyy") & ""
F1.ComboDashPtList.List(x, 3) = rs.Fields("MedNumber").Value & ""
rs.MoveNext
x = x + 1
Wend
rs.Close
Exit Sub`
'....
This is an example of how I send my data back to Access (again picking up mid-Sub).
` Set Conn = New ADODB.Connection
Set rs = New ADODB.Recordset
Conn.Open (strConn)
rs.Open strDBPtInfo, strConn, adOpenKeyset, adLockOptimistic, adCmdTable
rs.AddNew
rs!MedNumber = strMedNum
rs!LastName = strLastName
rs!Firstname = strFirstName
rs!DOB = dtDOB
rs.Update `
'....
Sometimes I need to completely overwrite or add to a specific field in a certain Access table. For years 'someone may have an allergy to penicillin, but suddenly they are also allergic to codeine, so that has to 'be updated. This is the approach I've taken but I keep getting an error:
'....
` Set Conn = New Connection
Set rs = New Recordset
Conn.Open (strConn)
strUpdateqry = "SELECT * FROM tblMedHxInfo WHERE MedNumber = " & Chr(34) & strMedNum & Chr(34) & ""
rs.Open strUpdateqry, strConn, adOpenKeyset
rs!Allergies = "Penicillin, Codeine"
rs.Update
If rs.State = 1 Then rs.Close
If Conn.State = 1 Then Conn.Close
Set rs = Nothing
Set Conn = Nothing`
....
This is the Error:
"Run-time error '3251': Current Recordset does not support updating.
This may ne a limitation of the provider, or of the selected locktype"
'Any help would be greatly appreciated!
'Thanks,
'Derek
'I've tried using the recordset to create a temporary table and then use that to update but it's getting over my head
Explicitly declare connection and recordset type. Then Set lines are not required.
Set the lock type argument.
Reference connection object not string variable for opening recordset.
Dim cn As ADODB.Connection, rs As ADODB.Recordset
cn.Open (strConn)
strUpdateqry = "SELECT * FROM tblMedHxInfo WHERE MedNumber = " & Chr(34) & strMedNum & Chr(34)
rs.Open strUpdateqry, cn, adOpenKeyset, adLockOptimistic
rs.Update "Allergies", "Penicillin, Codeine"
Or instead of opening recordset object for insert or update:
Dim cn As ADODB.Connection
cn.Open (strConn)
cn.Execute "UPDATE tblMedHxInfo SET Allergies = 'Penicillin, Codeine' WHERE MedNumber='" & strMedNum & "'"

Pass a value dynamically to SQL Server through VBA

Disclaimer: I am new to VBA.
I hope to pass the value in the SQL query (30881570) through a field on my Excel sheet. I have tried a few different things.
Private Sub cmdImport_Click()
Call cmdClear_Click
Dim conn As New ADODB.Connection, cmd As New ADODB.Command, rs As New ADODB.Recordset
With conn
.ConnectionString = _
"Provider=SQLOLEDB; " & _
"Data Source=PRGTAPPDBSWC019; " & _
"Initial Catalog=DETEP;" & _
"Integrated Security=SSPI;"
.Open
End With
With cmd
.ActiveConnection = conn
.CommandText = "SELECT * FROM [dbo].[tbl_PMHeader] WHERE [PMHeader_PM_NUM] = '30881570'"
.CommandType = adCmdText
End With
Set rs.Source = cmd
rs.Open
'Need this to populate header row, starting at specified Range
For intColIndex = 0 To rs.Fields.Count - 1
Range("B1").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
'This is where your data table will be copied to
ActiveSheet.Range("B2").CopyFromRecordset rs
Worksheets("Sheet1").Columns("B:BB").AutoFit
Worksheets("Sheet1").Range("A25").Formula = "=COUNTA(B:B)-1"
End Sub
It looks like you're already passing that value as criteria for the query's WHERE statement.
If you're asking how to replace that with a value from a worksheet, here's one way:
.CommandText = "SELECT * FROM [dbo].[tbl_PMHeader] " & _
"WHERE [PMHeader_PM_NUM] = '" & Sheets("mySheet").Range("A1") & "'"
...where your worksheet is named mySheet and the value is in cell A1.
This is the simplest method, potentially fine for internal use by trusted parties, but if the value has any ' single-quotes in it, you will get an error.
Worst-case scenario, this method leaves you open to SQL Injection attacks. Depends on your needs (and whether this this is just a school assignment), you may be better of using a parameter query.
See Also:
MSDN Blog : How and Why to Use Parameterized Queries
MSDN Blog : Everything About Using Parameters from Code
Private Sub cmdImport_Click()
Dim conn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim sqlStr As String
With conn
.ConnectionString = _
"Provider=SQLOLEDB; " & _
"Data Source=PRGTAPPDBSWC019; " & _
"Initial Catalog=DETEP;" & _
"Integrated Security=SSPI;"
.Open
End With
orderno = Sheets("Sheet1").Range("A22")
strSql = "SELECT * FROM [dbo].[tbl_PMHeader] " & _
"WHERE [PMHeader_PM_NUM] = " & orderno
With cmd
.ActiveConnection = conn
.CommandText = strSql
.CommandType = adCmdText
End With
'Call cmdClear_Click
Set rs.Source = cmd
rs.Open
'Need this to populate header row, starting at specified Range
For intColIndex = 0 To rs.Fields.Count - 1
Range("B1").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
'This is where your data table will be copied to
ActiveSheet.Range("B2").CopyFromRecordset rs
Worksheets("Sheet1").Columns("B:BB").AutoFit
Worksheets("Sheet1").Range("A25").Formula = "=COUNTA(B:B)-1"
End Sub

Cannot Update Date Fields in Excel Named Range with SQL Using ADODB from VBA

I am trying to run VBA-SQL to update existing entries in an excel table. The data will move to a DB, but not until after rollout and testing for an internal application for a small group. I have been able to update text (string) fields with the connection, but the date fields will not allow me to update. Only the Date Fields are a problem. The Microsoft.ACE API is recognizing them as date format.
The code is as follows, with both methods and respective errors in the code,
Dim Cn As ADODB.Connection
Dim RS As ADODB.Recordset
DBFullName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
Cnct = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & DBFullName & "';" & _
"Extended Properties='Excel 12.0 Macro;ReadOnly=0;HDR=Yes'"
Set Cn = New ADODB.Connection
Cn.Open ConnectionString:=Cnct
‘ Method #1
strSQL = “UPDATE StatusData SET [Last Update]=#2014-10-02 12:00:00# WHERE [Program Category]='Cat' AND [Program Name]='Prog' AND [LN] IS NULL AND [SN]='sn';”
Cn.Execute strSQL, RecordsAffected, adExecuteNoRecords
Error “Cannot update ‘(expression)’; field not updateable.”
‘ Method #2
strSQL = “SELECT * FROM StatusData WHERE [Program Category]='Cat' AND [Program Name]='Prog' AND [LN] IS NULL AND [SN]='sn';”
Set RS = New Recordset
RS.Open strSQL, Cn, adOpenDynamic, adLockOptimistic
RS.MoveFirst
RS.Fields("Last Update").Value = a '"#10/2/2014 04:00:00 PM#"
Error “Field Cannot Be Updated.”
RS.Update
RS.Close
Cn.Close
Set RS = Nothing
Set Cn = Nothing
Method #1 worked once the cell with the formula was removed from the field. Formulas are Read-only as well documented by Microsoft and other posts.

Query Access database and return all records to Excel

I am working on a macro whereby the user enters a search term which is used to query an Access Database. My question is how do I return those records to Excel in separate rows?
For example, a database contains home address information. If the user searches for a zip code, the records that are selected would go into row 1, 2, 3, etc. for as many home addresses as are returned in the query.
Below is some example code - the part I am missing is clearly marked.
I appreciate any help!
Sub DatabaseQuery()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim stDB As String, stSQL As String, stProvider As String
Dim SearchTerm As String
stDB = "Data Source= C:\Database.accdb" ' Change accordingly
stProvider = "Microsoft.ACE.OLEDB.12.0"
With cn
.ConnectionString = stDB
.Provider = stProvider
.Open
End With
SearchTerm = Range("A1").Value ' Change accordingly
stSQL = "SELECT Field1, Field2, Field3 " & _
"FROM Table1 WHERE Field4= '" & SearchTerm & "'"
rs.Open stSQL, cn, adOpenStatic
' *** Put all the records in Sheet2! *** Help me! :)
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
You need to tell us which version of Access you're using, as it would change a couple things.
Also, why is there even mention of a connection string? I don't see you saying you're using VB.NET. All I see is MS Access & Excel - Office applications.
When Access exports something to Excel, it would pretty much mimic the same look it did as if you looked at the Data in a DataSheet.
If you are using Access, check out this code I wrote as a starting point:
outputFileName = CurrentProject.Path & "\Reports\YourReportName.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "YourName", outputFileName, True
If you are using a different front end, you need to tell us in your question. Otherwise, how are we supposed to help you? By guessing? That's a good way to not get an answer.
I have learned there is more than 1 way to do this. The following does work for me.
Sub DatabaseQuery()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim stDB As String, stSQL As String, stProvider As String
Dim SearchTerm As String
stDB = "Data Source= C:\Database.accdb" ' Change accordingly
stProvider = "Microsoft.ACE.OLEDB.12.0"
With cn
.ConnectionString = stDB
.Provider = stProvider
.Open
End With
SearchTerm = Range("A1").Value ' Change accordingly
stSQL = "SELECT Field1, Field2, Field3 " & _
"FROM Table1 WHERE Field4= '" & SearchTerm & "'"
rs.Open stSQL, cn, adOpenStatic
Sheets("Sheet2").Range("A1").CopyFromRecordset rs
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub

Recordset in VB6.0

I'm retrieving Data from a Database in a record set using VB6... so while retrieving data using Select in SQL I added a column called Comments along wit it so that in the recordset, all the columns of the table+'Comments' column would be present... I don't want to(and also I cannot) update any contents in the database as i'm only 'fetching' data frm the database now...
Now when i pass the fetched data for validation, I want to fill the 'comments' Column with the respective errors if the particular row in the recordSet is erroneous).... When i do that i get an error saying "I'm not authorized to do that!!(to update the 'Comments' Column"....
Now My Question is "In what way i can solve this problem???".. I tried to replicate this recordset and there by now filling the 'comments'column (in the replicated one) which in turn showed the same error... It seems this could be because the duplicate one(recordSet) just retains the properties of the original one...
Can u any1 help how to solve this???? Any ways to replicate the recordset(without inheriting its properties something)??????
I think you are just asking how to do a disconnected recordset.
For that you just change the cursor location of the recordset.
Dim rstTest as ADODB.RecordSet
Set rstTest = New ADODB.RecordSet
With rstTest
.CursorLocation = adUseClient
.Open "your sql here", your_connection_object, adOpenStatic, adLockBatchOptimistic, adCmdText
' now disconnect it and force the local copy
.ActiveConnection = Nothing
End With
Not exactly what you are looking for, but this is how I do it:
Create a class to encapsulate the recordset ('Customer' class for 'Customer' table)
Add your Comment property to the class and not to recordset
Add a Validate method to your class. Have it write to your Comment property (I use an Errors Collection)
Read the recordset
Parse it into a "new Customer"
Validate
Check the Comment property (or the Errors Collection)
You can use the MSDataShape with its SHAPE..APPEND syntax to append a new Field to an ADO Recordset. Here's a quick example using Jet (a.k.a. MS Access):
Sub ShapeAppendField()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
Dim jeng
Set jeng = CreateObject("JRO.JetEngine")
jeng.RefreshCache .ActiveConnection
Set .ActiveConnection = Nothing
End With
Dim con
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;" & _
"Data Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
.CursorLocation = 3
.Open
.Execute _
"CREATE TABLE Test (" & _
"existing_col INTEGER NOT NULL);"
.Execute _
"INSERT INTO Test (existing_col)" & _
" VALUES (1);"
Dim rs
Set rs = CreateObject("ADODB.Recordset")
With rs
.CursorType = 2
.LockType = 4
.Source = _
"SHAPE {" & _
" SELECT existing_col" & _
" FROM Test" & _
"} APPEND NEW adInteger AS new_col"
Set .ActiveConnection = con
.Open
Set .ActiveConnection = Nothing
.Fields("new_col").value = 55
MsgBox .GetString
.Close
End With
End With
End Sub