VB.net从CSV文件创建联系人

时间:2015-01-13 07:18:40

标签: vb.net

我已经获得了这个代码,它似乎遍历了一个联系人列表,但是它不会创建一个Outlook联系人,也不会产生错误。任何想法?

 Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser("c:\contacts.csv")
    Dim CurrentRecord As String() ' this array will hold each line of data
    afile.TextFieldType = FileIO.FieldType.Delimited
    afile.Delimiters = New String() {vbTab}
    afile.HasFieldsEnclosedInQuotes = True


    Dim oApp As Outlook.Application
    oApp = CreateObject("Outlook.Application")

    Dim oNs As Outlook.NameSpace
    oNs = oApp.GetNamespace("MAPI")
    oNs.Logon()

    Dim oItem As Outlook.ContactItem
    oItem = oApp.CreateItem(OlItemType.olContactItem)

    ' parse the actual file
    Do While Not afile.EndOfData
        Try
            CurrentRecord = afile.ReadFields

            With oItem
                .FirstName = CurrentRecord(0)
                .LastName = CurrentRecord(1)
               End With

            oItem.Save()
        Catch ex As FileIO.MalformedLineException
            Stop
        End Try
    Loop
    MsgBox("Complete")
End Sub

不确定这是否是最好的方法,所以我愿意接受建议。

1 个答案:

答案 0 :(得分:0)

不知道这是否是整个问题,但你应该在循环中创建每个联系人(是的,我更喜欢“Do Until”而不是“Do While Not”):

Do Until afile.EndOfData
    Try
        CurrentRecord = afile.ReadFields
        oItem = oApp.CreateItem(OlItemType.olContactItem)
        With oItem
            .FirstName = CurrentRecord(0)
            .LastName = CurrentRecord(1)
            .Save()
        End With            
    Catch ex As FileIO.MalformedLineException
        Stop
    End Try
Loop