将CSV导入工作簿Excel VBA中的新工作表

我创建了从CREO导出的CSV BOM。我的主工作表上有一个命令按钮,它将把CSV导入到新的工作表中,并用CSV文件名命名工作表。 我遇到的问题是导入操作不会将日期添加到新工作表中,而是会打开一个新工作簿。

子load_csv()     昏暗的fStr作为字符串

With Application.FileDialog(msoFileDialogFilePicker)
    .Show
    If .SelectedItems.Count = 0 Then
        'MsgBox "Cancel Selected"
        Exit Sub
    End If
    'fStr is the file path and name of the file you selected.
    fStr = .SelectedItems(1)
End With

    Dim ws As Worksheet 'variable that will contain the new sheet

    Dim help_name() As String 'helper string array that will contain the full path of your file
    help_name = Split(fStr,"\") 'populating the variable with the full path,each '\' creates a new item

    Set ws = ThisWorkbook.Sheets.Add 'adding a new sheet to your workbook
    ws.Name = Replace(help_name(UBound(help_name)),".bom","",vbTextCompare) 'naming the new sheet with the name of the file and removing the '.bom'
        'ubound returns the highest position of the array,which is always name of the file

With ThisWorkbook.Sheets("Sheet2").QueryTables.Add(Connection:= _
"TEXT;" & fStr,Destination:=ThisWorkbook.Sheets("Sheet2").Range("$A$1"))
    .Name = "CAPTURE"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFiletabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1,1,1)
    .TextFileTrailingMinusnumbers = True
    .Refresh BackgroundQuery:=False
    'activeWorkbook.Save



End With

结束子

我已经创建了将CSV导入“ Sheet2”的代码,但是我希望将其添加为新的工作表,然后将该工作表重命名为文件名,如果可能的话,请在末尾添加.BOM。

heminminzjl 回答:将CSV导入工作簿Excel VBA中的新工作表

我希望这会有所帮助:-)

如果将其粘贴在with语句之前,然后在with语句中将'ThisWorkbook.Sheets(“ Sheet2”)'替换为'ws',我相信它应该做您需要的事情。

Dim ws As Worksheet 'variable that will contain the new sheet

Dim help_name() As String 'helper string array that will contain the full path of your file
help_name = Split(fstr,"\") 'populating the variable with the full path,each '\' creates a new item

Set ws = ThisWorkbook.Sheets.Add 'adding a new sheet to your workbook
'Original not reliable option 'ws.Name = Replace(help_name(UBound(help_name)),".bom","",vbTextCompare) 'naming the new sheet with the name of the file and removing the '.bom'
    'ubound returns the highest position of the array,which is always name of the file
ws.Name = Left(help_name(UBound(help_name)),InStr(1,help_name(UBound(help_name)),vbTextCompare) - 1) 'updated hopefully more reliable option of naming the sheet
本文链接:https://www.f2er.com/3152404.html

大家都在问