Advertisement

VBA 读文件

阅读量:
  1. 这是一个通过VBA读取文件的例子。作了两个button,一个用来启动程序,一个用来清除读出的文件内容。

  2. 共做了两个sheet,一个用来放button, 一个用来放读出来的数据。

  3. 文件内容

  4. ID=1234

  5. content=kasjdfiajewoirjawoerwer

  6. Private Sub ClearTable_Click() Call clearTableRecordEnd SubPrivate Sub Start_Click() Call doit Sheets("table").SelectEnd SubPublic folder As StringPublic ext As StringSub doit() folder = Worksheets("program").Range("C3").Value ext = Worksheets("program").Range("C4").Value With Application.FileSearch .NewSearch .fileName = ext .LookIn = folder If .Execute() > 0 Then Dim fileName As String Dim line As String pos = 3 For fileIdx = 1 To .FoundFiles.Count fileName = .FoundFiles(fileIdx) Set FSO = CreateObject("Scripting.FileSystemObject") Set fileStream = FSO.OpenTextFile(fileName, 1) idx = 1 record_status = 0 Do While fileStream.AtEndOfStream <> True line = fileStream.readline Worksheets("table").Cells(pos, 1) = fileName If StrComp(Left(line, 3), "ID=") = 0 Then RTrim (line) Worksheets("table").Cells(pos, 2) = Right(line, Len(line) - 3) record_status = record_status + 1 End If If StrComp(Left(line, 8), "content=") = 0 Then RTrim (line) Worksheets("table").Cells(pos, 3) = Right(line, Len(line) - 8) record_status = record_status + 1 End If idx = idx + 1 Loop If record_status = 2 Then pos = pos + 1 End If Next fileIdx Else MsgBox "There were no files found." End If End WithEnd SubSub clearTableRecord()'' cleartable Macro'' Sheets("table").Select Cells.Select Selection.Delete Shift:=xlUp Range("A2:C2").Select With Selection.Interior .ColorIndex = 15 .Pattern = xlSolid End With Selection.Borders(xlDiagonalDown).LineStyle = xlNone Selection.Borders(xlDiagonalUp).LineStyle = xlNone With Selection.Borders(xlEdgeLeft) .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With With Selection.Borders(xlEdgeTop) .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With With Selection.Borders(xlEdgeBottom) .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With With Selection.Borders(xlEdgeRight) .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With With Selection.Borders(xlInsideVertical) .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = xlAutomatic End With 'With Selection.Borders(xlInsideHorizontal) '.LineStyle = xlContinuous '.Weight = xlThin '.ColorIndex = xlAutomatic 'End With Range("A2").Select ActiveCell.FormulaR1C1 = "File Path" Range("B2").Select ActiveCell.FormulaR1C1 = "ID" Range("C2").Select ActiveCell.FormulaR1C1 = "CONTENT" Columns("A:C").Select Selection.ColumnWidth = 42 Range("A3").SelectEnd Sub

全部评论 (0)

还没有任何评论哟~