将列表从SharePoint导入到Excel作为范围(或使用固定的表名)

时间:2019-01-16 09:51:56

标签: excel vba sharepoint

所以我有下面的代码从SharePoint中提取列表并将其导入Excel。我的问题是,它将它导入为表而不是范围,并且由于每次运行脚本(表1,表2等)时表名都不相同,因此无法自动将其转换为范围。

我的问题如下:是否可以立即从SharePoint作为Excel Range导入列表,这样就不必进行转换?如果没有,我可以做到吗,所以每次运行导入过程时,导入表的名称都是固定的吗?

这是我的代码:

   Sub SharePoint_Import()
        Dim objMyList As ListObject
        Dim objWksheet As Worksheet
        Dim strSPServer As String
        Const SERVER As String = "xxxx.xxxxx.xxx.net/xxxx/xxxx" 'SP server
        Const LISTNAME As String = "{1234567-1234-1234-1234-1234567891}" 'SP List ID
        Const VIEWNAME As String = "" 

            Set RData = Sheets("rawdata") 'reset import sheet
            RData.UsedRange.ClearContents

        strSPServer = "https://" & SERVER & "/_vti_bin" '<- _vti_bin is necessary
        Set objWksheet = RData

          Set objMyList = objWksheet.ListObjects.Add(xlSrcExternal, Array(strSPServer, LISTNAME, VIEWNAME), False, , Range("A1"))
          Set objMyList = Nothing
          Set objWksheet = Nothing

    End Sub

2 个答案:

答案 0 :(得分:1)

执行此操作

[1]将RData.UsedRange.ClearContents更改为RData.Cells.Clear。这将完全清除纸张。删除格式,文本,表格等。

[2]导入表后,添加此代码。由于将只有一个表,因此您可以使用表号来处理它。

Dim tbl As ListObject
Set tbl = RData.ListObjects(1)

Dim tblRng As Range
Set tblRng = tbl.Range

'~~> Convert table to range
tbl.Unlist

'~~> Comment this in case you do not
'~~> want to remove the formatting
With tblRng
    .Interior.ColorIndex = xlColorIndexNone
    .Font.ColorIndex = xlColorIndexAutomatic
    .Borders.LineStyle = xlLineStyleNone
End With

答案 1 :(得分:0)

您可以使用ADODB查询Sharepoint列表。检查以下代码(未经测试,因为我没有Sharepoint,但过去使用过类似的东西)

Const SERVER As String = "xxxx.xxxxx.xxx.net/xxxx/xxxx" 'SP server
Const LISTNAME As String = "{1234567-1234-1234-1234-1234567891}" 'SP List ID

Dim connStr As String
Dim conn As New ADODB.Connection
Dim rs As ADODB.Recordset

connStr = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=1;RetrieveIds=Yes;" _
        & "DATABASE=" & SERVER _
        & ";LIST=" & LISTNAME & ";"
conn.Open connStr
Set rs = conn.Execute("select * from list")

Dim rData As Worksheet
Set rData = thisworknbook.Sheets("rawdata") 'reset import sheet
rData.UsedRange.ClearContents
rData.Range("A1").CopyFromRecordset rs
conn.Close