如何在VBA表单上显示部分Excel

时间:2012-11-23 10:50:11

标签: excel excel-vba excel-2007 userform vba

我有.csv格式的文件和A-S列,它有一些像桌子一样的记录。我的完整程序将插入/删除/删除/添加一些行,列和编辑单元格值等。我设法编写了我需要的所有操作,现在我正在尝试将它与gui集成。

我想要的是将Ax1中的单元格显示到在VBA用户表单上有记录的最后一列。我怎么能这样做?

* ps:再次,我的文件格式为.csv,我正在使用Excel 2007

1 个答案:

答案 0 :(得分:19)

您可以使用多列列表框来显示数据。

<强> LOGIC

  1. 导入临时表中的文本(Csv)文件
  2. 在多列列表框中显示数据
  3. 删除Userform卸载事件中的临时表
  4. 导入临时表中的文本(Csv)文件

    Private Sub CommandButton1_Click()
        Dim wb As Workbook, wbTemp As Workbook
        Dim wsTemp As Worksheet
    
        Set wb = ThisWorkbook
        Set wbTemp = Workbooks.Open("C:\MyCsv.Csv")
    
        wbTemp.Sheets(1).Copy After:=wb.Sheets(wb.Sheets.Count)
    
        Set wsTemp = ActiveSheet
    
        wbTemp.Close SaveChanges:=False
    End Sub
    

    现在,您可以在多列列表框中显示该数据。

    在多列列表框中显示数据

    我以3列为例,直至20列。更改为适用

    Private Sub CommandButton1_Click()
        Dim wb As Workbook, wbTemp As Workbook
        Dim wsTemp As Worksheet
    
        Set wb = ThisWorkbook
        Set wbTemp = Workbooks.Open("C:\MyCsv.Csv")
    
        wbTemp.Sheets(1).Copy After:=wb.Sheets(wb.Sheets.Count)
    
    
        Set wsTemp = ActiveSheet
    
        wbTemp.Close SaveChanges:=False
    
        With ListBox1
            .ColumnCount = 3
            .ColumnWidths = "50;50;50"
            .RowSource = wsTemp.Range("A1:C20").Address
        End With
    End Sub
    

    <强> SCREENSHOT

    enter image description here

    删除Userform卸载事件中的临时表

    要删除临时表,请在代码顶部声明wsTemp,以便您可以在UserForm_QueryClose事件中访问该代码。看到这个完整的例子

    Option Explicit
    
    Dim wsTemp As Worksheet
    
    Private Sub CommandButton1_Click()
        Dim wb As Workbook, wbTemp As Workbook
    
    
        Set wb = ThisWorkbook
        Set wbTemp = Workbooks.Open("C:\MyCsv.Csv")
    
        wbTemp.Sheets(1).Copy After:=wb.Sheets(wb.Sheets.Count)
    
    
        Set wsTemp = ActiveSheet
    
        wbTemp.Close SaveChanges:=False
    
        With ListBox1
            .ColumnCount = 3
            .ColumnWidths = "50;50;50"
            .RowSource = wsTemp.Range("A1:C20").Address
        End With
    End Sub
    
    Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
        Application.DisplayAlerts = False
        wsTemp.Delete
        Application.DisplayAlerts = True
    End Sub
    

    HTH