如何将csv下载到vba阵列?

时间:2013-10-22 06:36:06

标签: vba csv access-vba

我想将数据导入MS Access 2010表,但我导入的数据将取决于我下载的csv文件。因此,我需要先将URL文件从URL导入到某种VBA容器中。

This post seems to discuss the loading of CSV files into vba arrays, but not from a URL...

到目前为止,我已经这样做了下载CSV文件:

Public Function GetFileFromURL(ByVal url As String) As Object

Dim myURL As String
myURL = "http://www.somesite.com/file.csv"

Set GetFileFromURL = CreateObject("Microsoft.XMLHTTP")
GetFileFromURL.Open "GET", myURL, False
GetFileFromURL.Send

End Function

Sub DownloadSomething()

GetFileFromURL("ichart.yahoo.com/table.csv?s=GOOG&a=0&b=1&c=2000&d=0&e=31&f=2010&g=d&ignore=.csv")

End Sub

这样运行,但我不知道如何处理GetFileFromURL对象;在这一点上,它可能只是一个字符串列表,但我怎么能得到它们,当我这样做时,如何将它们转换为数组呢?

1 个答案:

答案 0 :(得分:1)

我不知道这是否会对你有所帮助。这是我用于质量控制程序的例程。 csv文件有4行,最多20行,因此arrData(80)但它也可以少于20行。我用这个来从一个autocad绘图中获取尺寸(从不超过20)并填写文本框。

Kim是正确的,每次都必须采用相同形式的csv格式。

Private Sub Import_Click()
   On Error GoTo HandleError
    RoutineName = Form.Name & " Import_Click Event"

    Dim Detline As String        'Record form selected file
    Dim I As Integer             'Index for rows (table & array)
    Dim FF As Integer            'next file number available for use by the Open statement
    Dim dlgOpen As FileDialog

    Set dlgOpen = Application.FileDialog(msoFileDialogOpen)
    With dlgOpen
        With .Filters
            .Clear
            .Add "Import csv or txt", "*.csv; *.txt", 1
            .Add "All Files", "*.*", 2
    End With
     .InitialFileName = "c:\QControl\"
    .FilterIndex = 1
    .AllowMultiSelect = False
    .Title = "Select document to import"
    .ButtonName = "Ok"
    .Show
    If .SelectedItems.Count > 0 Then
        SelectedFile = .SelectedItems(1)
    End If

End With

ReDim arrData(80)
DoCmd.GoToRecord acDataForm, "Main QC Form", acNewRec
I = 1                        ' initalize counter
FF = FreeFile                'Use FreeFile to supply a file number that is not already in use.
Open SelectedFile For Input As #FF
Do While Not EOF(FF)         'Read selected file line by line
  Line Input #FF, Detline
  arrData = Split(Detline, ",")
  Me.Controls("letter" & I) = arrData(0)
  Me.Controls("printdim" & I) = arrData(1)
  Me.Controls("stepnumber" & I) = arrData(2)
  Me.Controls("Gage" & I) = arrData(3)
  I = I + 1   'increment counter
Loop

RunCommand acCmdSaveRecord ' Save the Record you're looking at
Me.Requery ' Force the Recordset of the Form to update
Me.Form1.Requery

Close #FF   'close text file
DoCmd.GoToRecord , , acLast

Exit_Import_Click:
    DoCmd.SetWarnings True
    Exit Sub
HandleError:
    RtnCode = ErrorHandler   (EH_NumError:=Err.Number,DescError:=
   Err.Description,NameRoutine:=RoutineName)

   Resume Exit_Import_Click
 End Sub