前段时间用vb做了一个小软件,用来将下位机存储的运行记录(txt格式)转为excel格式。 源代码如下,供需要借鉴的朋友来下载,代码有点乱,但是功能是经过验证了的。本来是想将工程作为附件插入进来,弄了半天居然没有发现这个功能,有点无语,直接上代码吧。
Public xx As String
Public temp As String
Public file_length As Long
Public file_number As Long

Private Sub Command1_Click()
ProgressBar1.Visible = True
Dim H() As String, L() As String, i As Integer, j As Integer, a() As String
Dim SaveFile As String
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Set xlApp = CreateObject("Excel.Application") '创建EXCEL对象
Set xlBook = xlApp.Workbooks.Add '打开已经存在的EXCEL工件簿文件
xlApp.Visible = True '设置EXCEL对象可见(或不可见)
Set xlSheet = xlBook.Worksheets("Sheet1") '设置活动工作表
'*************************************************************
Open xx For Input As #1 'open the file
xlSheet.Cells(1, 1) = "序号"
xlSheet.Cells(1, 2) = "时间"
xlSheet.Cells(1, 3) = "模式"
xlSheet.Cells(1, 4) = "电流(A)"
xlSheet.Cells(1, 5) = "总电压(V)"
xlSheet.Cells(1, 6) = "容量(AH)"
xlSheet.Cells(1, 7) = "告警类型"
xlSheet.Cells(1, 8) = "环境温度(C)"
xlSheet.Cells(1, 9) = "电池温度1"
xlSheet.Cells(1, 10) = "电池温度2"
xlSheet.Cells(1, 11) = "电池温度3"
xlSheet.Cells(1, 12) = "电池温度4"
xlSheet.Cells(1, 13) = "电池温度4"
xlSheet.Cells(1, 14) = "电压1"
xlSheet.Cells(1, 15) = "电压2"
xlSheet.Cells(1, 16) = "电压3"
xlSheet.Cells(1, 17) = "电压4"
xlSheet.Cells(1, 18) = "电压5"
xlSheet.Cells(1, 19) = "电压6"
xlSheet.Cells(1, 20) = "电压7"
xlSheet.Cells(1, 21) = "电压8"
xlSheet.Cells(1, 22) = "电压9"
xlSheet.Cells(1, 23) = "电压10"
xlSheet.Cells(1, 24) = "电压11"
xlSheet.Cells(1, 25) = "电压12"
xlSheet.Cells(1, 26) = "电压13"
xlSheet.Cells(1, 27) = "电压14"
xlSheet.Cells(1, 28) = "电压15"
xlSheet.Cells(1, 29) = "电压16"
For j = 0 To file_number
Line Input #1, temp
H = Split(temp, vbTab)
For i = 0 To file_length - 1
xlSheet.Cells(j + 2, i + 1) = H(i)
ProgressBar1.Value = i + 1
Next i
Next j
Close #1 'close the file
SaveFile = "c:\yu.xls"
If Dir(SaveFile) <> "" Then Kill SaveFile
xlBook.SaveAs FileName:=SaveFile '保存工作表,结束时一定别忘了保存
xlBook.Close (True) '关闭工作簿 这里的True表示退出时保存修改
xlApp.Quit '结束EXCEL对象
Set xlApp = Nothing '释放xlApp对象
MsgBox "文件已成功导出到" & SaveFile
End Sub
Private Sub Command2_Click()
txt_file.FileName = ""
txt_file.Flags = vbOFNFileMustExist
txt_file.Filter = "All Files|*.*|(*.txt)|*.txt"
txt_file.FilterIndex = 2
txt_file.DialogTitle = "选择需要转换的Txt文件"
txt_file.Action = 1
If txt_file.FileName = "" Then
Else
xx = txt_file.FileName

Open xx For Input As #1 'open the file
Line Input #1, temp
a = Split(temp, vbTab)
file_length = UBound(a) - LBound(a) + 1
ProgressBar1.Max = file_length
Do While Not EOF(1)
Line Input #1, temp
file_number = file_number + 1
Loop
file_number = file_number
Close #1 'close the file
End If
End Sub
Private Sub Form_Load()
xx = ""
file_length = 0
file_number = 0
ProgressBar1.Visible = False
End Sub