提问人:Andrew Smith 提问时间:6/23/2023 最后编辑:Andrew Smith 更新时间:6/24/2023 访问量:270
打开 .csv 文件,更改列格式并保存为 VBA
Open .csv file, change column format and save in VBA
问:
我无法破解这个......谁能帮忙?我每天都会通过电子邮件向我发送许多文件,并且我有一个例程将这些文件保存在网络共享上。原始 Excel csv 文件在 A 列和 B 列中的日期字段为“DD/MM/YYYY 00:00:00”,我需要它是“DD/MM/YY”。我可以通过打开每个文件、选择列、更改列格式和保存来做到这一点,但我无法让它在 VBA 中自动化。我的代码的当前迭代(我已经多次使用这个块)如下。当我运行此代码时,它会将文件保存在新位置,但列的重新格式化不起作用,列保持原始格式:-(
Function F_PREPARE_GENESYS_FILES()
'Finds current day Genesys files on K: drive, copies them to another folder and changes format before data import process
On Error GoTo F_PREPARE_GENESYS_FILES_Err
Dim db As Database
Dim App As New Excel.Application
Dim MyFolder As String
Dim MyFile As String
Dim MyFile2 As String
Dim wbk As Excel.Workbook
Dim FSO As New FileSystemObject
Dim FromPath As String
Dim ToPath As String
Dim FileName As Variant
Set db = CurrentDb
FromPath = "\\chs114file1\dovpasres$\Statistics\Totem\Genesys_reports\"
ToPath = "\\chs114file1\dovpasres$\Statistics\Totem\RunTime\"
FileName = Format([Forms]![Processing]![ProcessDate], "yyyy-mm-dd_") & "*"
FSO.CopyFile FromPath & FileName, ToPath
MyFile = Dir(ToPath)
'Loop through all files in a folder until DIR cannot find anymore
Do While MyFile <> ""
Set wbk = App.Workbooks.Open(FileName:=ToPath & MyFile)
MyFile2 = Left(MyFile, Len(MyFile) - 4)
Sheets(MyFile2).Select
Range("A:B").NumberFormat = "m/d/yyyy"
ActiveWorkbook.Close savechanges:=True, FileName:=MyFile
'wbk.SaveAs MyFile, xlCSVUTF8
MyFile = Dir 'DIR gets the next file in the folder
Loop
答:
编辑
我怀疑认为“Excel csv 文件”是错误的,因为 CSV 文件只不过是纯文本。当 Excel 打开它们时,它会将内容读取为文本。显示为“DD/MM/YYYY 00:00:00”的日期只是文本。Excel 无法重新格式化它们,除非它将它们视为日期,因此 的变体无济于事。Range("A:B").NumberFormat = "dd/mm/yyyy"
处理此问题的一种方法是在临时列中添加一个公式,该公式将文本转换为实际日期,并根据需要设置该列的格式。然后你可以把它放在你需要的地方。下面的简单示例在 B 列中创建公式,覆盖 A 列中的输入文本日期,然后删除临时公式。在您的情况下,语句应根据需要向右偏移。该语句应引用该列数。例如,如果公式位于 E 列中,则 in 应为 。Copy - PasteSpecial
PasteSpecial
Set rngFormula
.FormulaR1C1
c[-1]
"=DATEVALUE(r[0]c[-1])
c[-4]
Option Explicit
Sub DateConvert()
Dim rngInput As Range, rngFormula As Range
Set rngInput = ActiveSheet.Cells(2, 1).Resize(5, 1) ' Input in Column A
Set rngFormula = rngInput.Offset(0, 1) ' Temp formula in Column B
With rngFormula
.FormulaR1C1 = "=DATEVALUE(r[0]c[-1])" ' Same row, 1 column to left
.NumberFormat = "DD/MM/YYYY"
.Copy
rngInput.PasteSpecial xlPasteValuesAndNumberFormats
.Clear ' Delete the temp formula
End With
End Sub
这将在单独的列中显示输出(抱歉,我的输入文本日期是 mm/dd/yyyy,但输出是正确的):
一个 | B | |
---|---|---|
1 | 文本输入“DD/MM/YYYY 00:00:00” | Excel 日期(输出) |
2 | 1/31/2023 12:34:56 | 31/1/2023 |
3 | 2/28/2023 12:34:56 | 28/2/2023 |
4 | 3/31/2023 12:34:56 | 31/3/2023 |
5 | 4/30/2023 12:34:56 | 30/4/2023 |
6 | 12/31/2023 12:34:56 | 31/12/2023 |
评论
上一个:更改记录中的日期
评论
Range("A:B").NumberFormat = "dd/mm/yyyy"
Range("A:B").NumberFormatLocal = "dd/mm/yyyy"
??