我正在尝试将CSV文件导入到我当前的工作簿中;但是,它会自动格式化我的一些数据。有没有办法防止这种情况?
示例:
01JAN-1
自动转换为:
1-JAN-01
我查找了添加Local:= true
,但我不确定如何实现。我试过了wb = Workbooks.Open(fileImportName, Local:=True)
代码:
Sub file_Import()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim fileImportPath As String, fileImportName As String, total As Integer, currentWorkbook As String
fileImportPath = "C:\Users\UserName\Desktop\Test Data.csv"
fileImportName = "Test Data.csv"
currentWorkbook = "Testing Import.xlsm"
total = Workbooks(currentWorkbook).Worksheets.Count
Workbooks.Open (fileImportName)
Workbooks(fileImportName).Worksheets(Sheets(1).Name).Copy _
After:=Workbooks(currentWorkbook).Worksheets(total)
Workbooks(fileImportName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
答案 0 :(得分:1)
下面的代码试图覆盖第一个工作表的内容。在运行之前保存工作簿的副本以确保安全。您需要提供CSV的完整路径。我假设您在CSV的每一行都有相同数量的列:
Option explicit
Sub CSVtoSheet()
Const FILEPATH as string = "C:\New Folder\test.csv" 'Replace with your own path; or consider changing to variable and assign dynamically.'
Const DELIMITER as string = ","
' Read into memory; assumes file will fit and is not too big.'
Dim FileContents as string
Open FILEPATH for binary access read as #1
Filecontents = space$(lof(1))
Get #1, 1, filecontents
Close #1
' Assign lines in file to 1-dimensional, 0-based array of strings'
Dim AllLines() as string
AllLines = split(filecontents,vbNewLine)
Dim NumberOfRows as long
Dim NumberOfColumns as long
NumberOfRows = ubound(alllines)+1'Watch out if last line of CSV is blank, as is sometimes the case. Rows which do not contain column delimiter can produce error/unwanted behaviour.'
' Assume number or columns is fixed throughout CSV and can be reliably deduced from first line alone'
NumberOfColumns = ubound(split(alllines(lbound(alllines)),delimiter))+1
Dim ArrayToWriteToSheet() as string 'Change to as variant if you need numeric values as numbers'
Redim ArrayToWriteToSheet(1 to NumberOfRows, 1 to NumberOfColumns)
' Iterate through each element in array'
Dim RowIndex as long, ColumnIndex as long
Dim TemporaryArray() as string
For RowIndex = lbound(arraytowritetosheet,1) to ubound(arraytowritetosheet,1)
If Len(alllines(rowindex-1)) > 0 then ' Skip any blank lines; sometimes final line in CSV is empty which can result in errors/unwanted behaviour.'
TemporaryArray = split(alllines(rowindex-1),delimiter)
For ColumnIndex = lbound(arraytowritetosheet,2) to ubound(arraytowritetosheet,2)
Arraytowritetosheet(RowIndex,ColumnIndex) = temporaryarray(columnindex-1)
Next columnindex
End if
Next rowindex
'Write to first sheet in workbook. Hopefully, Excel will not do any unwanted auto-conversion.'
Thisworkbook.worksheets(1).range("A1"). Resize(ubound(arraytowritetosheet,1),ubound(arraytowritetosheet,2)).value2 = arraytowritetosheet
End sub
它能做到你想要的吗?从理论上讲,一旦你在内存中拥有了这些值,你就可以在写回工作表之前格式化/呈现你想要的内容。
未经测试,写在手机上。