EXCEL数据输出到平面文件的宏代码

'使用注意事项: 第一列不能为空值,随便写入序号,第一行为字段名称不能为空


'定义文本文件对象,输出路径
Dim MyTXT As String, Path As String
Dim i, j, Row, Column, RowCount, ColumnCount As Integer

'定义2 dimension数组
Dim Data(100, 100) As String

'定义1 dimension数值

'define temp value
Dim IfExistValue As String
Dim TempString As String

Sub GenFile()

    '出现错误就结束
    On Error GoTo 0
   
    '行数的判断
    For i = 2 To 300
        IfExistValue = Cells(i, 1)
        If IfExistValue = "" Then
            RowCount = i - 1
            Exit For
        End If
    Next
    '列数的判断
    For j = 2 To 300
        IfExistValue = Cells(1, j)
        If IfExistValue = "" Then
            ColumnCount = j - 1
            Exit For
        End If
    Next
   
    'MsgBox RowCount
    'MsgBox ColumnCount
    'End
   
     '自定义存储名称
    Name = InputBox("输入要存储的文件名称,默认Example.CIF。")
   
    '与表格路径相同
    Path = Application.ThisWorkbook.Path & Application.PathSeparator
   
    '要转存的TXT文件全称
    If Name = "" Then
        MyTXT = Path & Name & "Example.CIF"
    Else
        MyTXT = Path & Name
    End If
   
    '循环取值 ,先定义1~7列1~11行中的单元格的数据为指定的变量Data1(1)至Data7(11)
    For Row = 2 To RowCount
            For Column = 1 To ColumnCount
           
'                If Len(Str(Column)) < 2 Then
'                   temp = "0" & Str(Column)
'                End If
'                temp = "Data" & temp & "(Row)"
'                temp = Cells(Row, Column)
'                Debug.Print temp
                Data(Row, Column) = Cells(Row, Column) '" " & Cells(Row, Column) & " "
               
            Next Column
    Next Row
   
    '将预定的变量值逐个输入到文件,格式为数据之间双竖线分隔,按行排列
    Open MyTXT For Output As #1
         For Row = 2 To RowCount
'            Print #1, Data01(Row) & "||" & Data02(Row) & "||" & Data03(Row) & "||" & Data04(Row) & "||" & Data05(Row) & "||" & _
'            Data06(Row) & "||" & Data07(Row) & "||" & Data08(Row) & "||" & Data09(Row) & "||" & Data10(Row) & "||" & _
'            Data11(Row) & "||" & Data12(Row) & "||" & Data13(Row) & "||" & Data14(Row) & "||" & Data15(Row) & "||"
            TempString = ""
            For Column = 2 To ColumnCount
                If Column = ColumnCount Then
                    TempString = TempString & Data(Row, Column) & " ||"
                Else
                    TempString = TempString & Data(Row, Column) & " || "
                End If
            Next Column
            Print #1, TempString
         Next Row
    Close #1
  
0 End Sub 

你可能感兴趣的:(String,Excel,Integer,存储,Path,output)