寻找一个宏来打开打开的工作簿中的特定工作表中的.csv文件

时间:2019-06-18 18:08:10

标签: excel vba

我的目标是要有一个运行宏的按钮,首先选择我要导入的.csv,然后将.csv复制到工作簿上的特定工作表上,这可能吗?该按钮将位于名为“ CONVERSION”的工作表上,.csv应该复制到“ IMPORT”。到目前为止,我已经在论坛上尝试了几篇文章,但都没有成功。

据我所知,没有错误

Sub load_csv() 
Dim fStr As String 
  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 
End Sub 

2 个答案:

答案 0 :(得分:0)

类似的事情应该对您有用:

Sub load_csv()

    Dim fStr As String

    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

    With ThisWorkbook.Worksheets("IMPORT").QueryTables.Add(Connection:="TEXT;" & fStr, Destination:=Range("A1"))
        .RefreshStyle = xlInsertDeleteCells
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileCommaDelimiter = True
        .Refresh BackgroundQuery:=False
    End With

End Sub

答案 1 :(得分:0)

以下内容将打开您的csv,并相应地允许复制/粘贴。

x = ActiveWorkbook.Name
y = Application.GetOpenFilename 'Opens dialog box and sets y to selected file
Workbooks.OpenText Filename:= y, Origin:=65001, StartRow:=1, DataType:=xlDelimited, TextQualifier:= xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2,1)), TrailingMinusNumbers:=True 'more arrays for more columns if you have them...  this code is for the text import wizard.
y = ActiveWorkbook.Name 'renames the file to the open file

Workbooks(y).ActiveSheet.Range("A1").Copy 'use a different sheet and range depending on what you are trying to copy.
Workbooks(x).ActiveSheet(Range("A1").PasteSpecial xlPasteValues 'use a different sheet or range depending on paste area