我正在尝试将文件夹中的所有csv文件导入到Excel文件中的新工作表中,同时保留文本格式。
我通过一些研究拼凑了一些代码并使其几乎按照我需要的方式工作,但是当我运行宏时,所有列都设置为General。
非常感谢对此的任何见解。
Sub ImportCSV()
Application.ScreenUpdating = False
Const conSpath As String = "C:\MyPath\"
Dim sMasterFile As String
Dim sSheetName As String
Dim sFile As String
Dim iNextSheet As Integer
ChDir conSpath
sMasterFile = ActiveWorkbook.Name
iNextSheet = Sheets.Count
sFile = Dir(conSpath & "*.csv", vbNormal)
While sFile <> ""
Workbooks.OpenText Filename:=sFile, _
Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlTextQualifierDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, _
Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 2), _
Array(2, 2), Array(3, 2), Array(4, 2), Array(5, 2)), TrailingMinusNumbers:=True
sSheetName = ActiveSheet.Name
Sheets(sSheetName).Copy After:=Workbooks(sMasterFile).Sheets(iNextSheet)
Workbooks(sFile).Close SaveChanges:=False
iNextSheet = iNextSheet + 1
sFile = Dir
Wend
Application.ScreenUpdating = True
End Sub
编辑:我能够将列更改为文本,但我仍然丢失了我的前导零。
Sub ImportCSV()
Application.ScreenUpdating = False
Const conSpath As String = "C:\MyPath\"
Dim sMasterFile As String
Dim sSheetName As String
Dim sFile As String
Dim iNextSheet As Integer
ChDir conSpath
sMasterFile = ActiveWorkbook.Name
iNextSheet = Sheets.count
sFile = Dir(conSpath & "*.csv", vbNormal)
While sFile <> ""
Workbooks.OpenText FileName:=sFile, _
Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlTextQualifierDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, _
FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 2), _
Array(5, 2)), TrailingMinusNumbers:=True
sSheetName = ActiveSheet.Name: Sheets(sSheetName).Cells.NumberFormat = "@"
Sheets(sSheetName).Copy After:=Workbooks(sMasterFile).Sheets(iNextSheet)
Workbooks(sFile).Close True
iNextSheet = iNextSheet + 1
sFile = Dir
Wend
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:0)
WorksheetFunction.Text
方法可能会解决前导零问题。这允许您在要格式化为文本的单个数字上设置格式。
如果您的数字(包括前导零)的长度都相同,您可以使用包含数值的单元格范围执行类似的操作:
Sub ConvertToTextWithLeadingZeros()
Dim rngText As Range
Set rngText = Selection
Dim rngCell As Range
Dim strText As String
For Each rngCell In rngText
strText = WorksheetFunction.Text(rngCell, "000000")
rngCell.NumberFormat = "@"
rngCell.value = strText
Next rngCell
End Sub
只需将"0000000"
设置为包含等于所需位数的零(包括前导零)。
答案 1 :(得分:0)
我通过以下方式解决了使用VBA处理csv文件的“丢失的开头零”问题:
main function
重要的是属性.TextFileColumnDataTypes = Array(2,2,2,2,2,2,2,2,2,2,2,2,2,2,2)
每个文本列都需要一个“ 2”。