在后台打开CSV文件并检索工作表名称

时间:2017-05-08 22:18:10

标签: excel vba excel-vba csv worksheet

我的VBA项目包括清理数据库。

我正在使用Userform,这是我现在写的代码。

我成功导入了一个文件,但我仍然无法对其执行操作。

  1. 我需要你们告诉我如何获取我刚刚导入的.csv文件的工作簿名称和工作表,以开始通过工作簿名称和工作表名称分配引用数据库的操作。
  2. 如果你能告诉我如何保持我的用户形式,或者如何导入.csv文件而不显示它,我也很感激
  3. Dim fNameAndPath As Variant
    
    Private Sub importedworkbook_Click()
    MsgBox "imported workbook : " & _
    fNameAndPath
    End Sub
    
    
    Private Sub Importbutton_Click()
    
    fNameAndPath = Application.GetOpenFilename(FileFilter:="CSV Files Only (*.CSV), *.XLS", Title:="Select File To Be Opened")
    If fNameAndPath = False Then Exit Sub
    Workbooks.Open Filename:=fNameAndPath
    End Sub
    

2 个答案:

答案 0 :(得分:1)

最好使用声明的变量来引用打开的CSV表

            HashMap<String,Book> hashMap = HashMap<String,Book>) getIntent().getSerializableExtra("hashMap");
            hashMap.put(bookIsbn,new Book(bookTitle,bookIsbn,bookFee,bookAuthor));
            finish();

变量Private wsCSV as Worksheet Private Sub Importbutton_Click() Dim wb as Workbook fNameAndPath = Application.GetOpenFilename(FileFilter:="CSV Files Only (*.CSV), *.XLS", Title:="Select File To Be Opened") If fNameAndPath = False Then Exit Sub Set wb = Workbooks.Open(Filename:=fNameAndPath) Set wsCSV = wb.Worksheets(1) ' A csv file will only ever have one sheet End Sub 现在引用CSV工作表,可以在UserForm模块的其他代码中引用

答案 1 :(得分:0)

您可以打开第二个Excel实例以使用隐藏文件

    Dim objExcel As Excel.Application
    Dim wb As Workbook
    fNameAndPath = Application.GetOpenFilename(FileFilter:="CSV Files Only (*.CSV), *.XLS", Title:="Select File To Be Opened")
    If fNameAndPath = False Then Exit Sub

    Set objExcel = New Excel.Application
    Set wb = objExcel.Workbooks.Open(fNameAndPath)
    Set wsCSV = wb.Worksheets(1)

    MsgBox wsCSV.Name
    ' do stuff

    'close second instance  
    wb.Close False
    objExcel.Quit
    Set objExcel = Nothing