2011-02-12 151 views
1

这是我写的代码,首先以excel打开一个csv文件,然后找到所需的三列,n然后从它们读取数据n将数据保存到另一个变量中,显示它们文本框。至于csv文件,它包含许多列,我的注意力集中在标题ID L,Lg下的3列上。使用VB从csv文件中读取数据

问题是Excel实际上并未打开,但Excel.exe进程在任务管理器中运行。 但是由于这一点它不是编译错误;编译错误出现在'Next'语句中。它说编译错误:Next没有For!

我对此感到困惑。请帮助我这个,在此先感谢。

私人小组cmdFind_Click()

Dim xlApp As Excel.Application 
Set xlApp = New Excel.Application 

Dim X As Double, Y As Double, FleetID As String 
Dim F As String, FCol As Integer, LCol As Integer, LgCol As Integer, Srno As Integer, I As Integer 


Dim xlWbook As Workbook 
Dim xlSht As Excel.Worksheet 
Set xlWbook = xlApp.Workbooks.Open("C:\Users\saurabhvyas\Desktop\test VB2\testfile.csv") 
xlApp.Visible = True 
Set xlSht = xlWbook.Worksheets("sheet1") 


For I = 1 To 8 Step 1 
    If xlSht.Cells(I, 1).Value = "ID" Then 
     FCol = I 
    Else 
    If xlSht.Cells(I, 1).Value = "L" Then 
     LCol = I 
    Else 
    If xlSht.Cells(I, 1).Value = "Lg" Then 
     LgCol = I 
    End If 
Next I 


Set Srno = 2 
Do 
    If xlSht.Cells(FCol, Srno).Value = Str$(txtF.Text) Then 
     Set X = xlSht.Cells(LCol, Srno).Value 
     Set Y = xlSht.Cells(LgCol, Srno).Value 
    End If 
    Srno = Srno + 1 
Loop While xlSht.Cells(FCol, Srno).Value = vbNullString 


txtL.Text = Str$(X) 
txtLg.Text = Str$(Y) 

xlWbook.Close 
xlApp.Quit 
Excel.Application.Close 
Set xlSht = Nothing 
Set xlWbook = Nothing 
Set xlApp = Nothing 

末次

回答

1

您可以打开CSV格式的文本文件,并使用ADO与Jet提供的文本IISAM对它们进行操作。比自动化Excel更笨拙。或者你可以用逗号读取文本和Split()。

你在做什么打开Excel,但你没有要求Excel可见......但我不知道你为什么要这样做。

你真的想做什么?

+0

是的,如果是单纯读特定列,然后点击文本IISAM是suficient。 – ramu 2011-03-03 12:53:59

+0

嗨,Thanx 4编译错误。 L是纬度,Lg是经度。我试图从一个csv文件读取许多ID中的一个。我的目的是读取这些值。 – 2011-03-05 13:26:57

1

至于你的编译错误,那是因为你错过了一些End Ifs。 把它写成:

For I = 1 To 8 Step 1 
    If xlSht.Cells(I, 1).Value = "ID" Then 
     FCol = I 
    Else 
     If xlSht.Cells(I, 1).Value = "L" Then 
      LCol = I 
     Else 
      If xlSht.Cells(I, 1).Value = "Lg" Then 
       LgCol = I 
      End If 
     End If 
    End If 
Next I 

或者为:

For I = 1 To 8 Step 1 
    If xlSht.Cells(I, 1).Value = "ID" Then 
     FCol = I 
    ElseIf xlSht.Cells(I, 1).Value = "L" Then 
     LCol = I 
    ElseIf xlSht.Cells(I, 1).Value = "Lg" Then 
     LgCol = I 
    End If 
Next I