从Excel导出到txt保留特殊日期格式

时间:2013-01-22 14:50:39

标签: excel file date text format

我一直在使用代码将数据从excel复制到.txt,删除任何不需要的字符,以便输入到另一个应用程序:

Public DirRoot As String
Public CasNam As String

Public Sub Export()

    Dim intUnit As Integer
    Dim rngRow As Range
    Dim rngCell As Range
    Dim strText As String

    intUnit = FreeFile

    DirRoot = "C:\temp\"
    CasNam = "Test"

        Open DirRoot & CasNam & ".txt" For Output As intUnit

    'End If

    With Worksheets("Export").UsedRange
        For Each rngRow In .Rows
            strText = ""
            For Each rngCell In rngRow.Cells
                If Len(rngCell.Value) = 0 Then Exit For
                strText = strText & " " & rngCell.Value
            Next
            Print #intUnit, Trim(strText)
        Next
    End With

    Close intUnit

End Sub

现在我需要在一组不同的数据下使用它,其中一列是格式为yyyymmdd的日期,当我应用上面的代码时,我得到的格式为{{1 }}

有什么办法可以将原始日期格式从excel保存到dd/mm/yyyy

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

更改此行

      strText = strText & " " & rngCell.Value

      strText = strText & " " &  Format(rngCell.Value,"yyyymmdd")
祝你好运

修改

请检查一下。 colCounter用于标识您的格式requeried列。

Dim colCounter as Integer
colCounter = 1
With Worksheets("Export").UsedRange
   For Each rngRow In .Rows
      strText = ""
      colCounter = 1
      For Each rngCell In rngRow.Cells
        If Len(rngCell.Value) = 0 Then Exit For
        If colCounter = 2  Then ' change 2 to whatever column you want to format
           strText = strText & " " &  Format(rngCell.Value,"yyyymmdd")
        Else
           strText = strText & " " & rngCell.Value
        End if
        colCounter = colCounter + 1
      Next
      Print #intUnit, Trim(strText)
   Next
End With

答案 1 :(得分:0)

我不太清楚哪个部分用日期声明变量,但这个解释可能会有所帮助:

Sub Date_Convert 

dim dtDate_Orig as date
dim dtDate_Convert as date
dim sDate as String


dtDate_Orig = "22/01/2012"
dtDate_Convert = format(dtDate_Orig, "yyyymmdd")
sDate = Cstr(dtDate_Convert)

'Now you can use the string for a filename 

End Sub

答案 2 :(得分:0)

这是你在尝试的吗?

'~~> Change this to the column which has dates
Col = 2

For Each rngCell In rngRow.Cells
    If Len(rngCell.Value) = 0 Then Exit For

    If rngCell.Column = Col Then
        strText = strText & " " & Format(rngCell.Value, "yyyymmdd")
    Else
        strText = strText & " " & rngCell.Value
    End If
Next