下面的VBA代码执行以下操作:
我付出了很多努力,仍然无法提出更好的方法来优化代码。
代码如下:
Private Sub Button_Browse_Click()
Dim sFileName As String
sFileName = Application.GetOpenFilename()
Text_Browse.Text = sFileName
End Sub
Private Sub Button_Close_Click()
Unload Me
End Sub
Private Sub Button_Convert_Click()
Dim myarray() As Variant
MyPath = Text_Browse.Text
For i = 0 To 16384
ReDim Preserve myarray(i)
myarray(i) = 2
Next i
With ActiveWorkbook.Sheets(2).QueryTables.Add(Connection:="TEXT;" & MyPath, Destination:=ActiveWorkbook.Sheets(2).Range("A1"))
.Name = "test"
.FieldNames = True
.AdjustColumnWidth = True
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = myarray
.Refresh BackgroundQuery:=False
Set NewBook = Workbooks.Add
Workbooks("CSV_Converter.xlsm").Sheets(2).Range("A1:XFD1048576").Copy
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
NewBook.SaveAs Filename:=MyPath + "_converted.xlsx"
ActiveWorkbook.Close
End With
End Sub