How To Display Part of Excel on VBA Form

一世执手 提交于 2019-11-29 10:20:55

You can use a multi column Listbox to show the data.

LOGIC

  1. Import the text (Csv) file in the temp sheet
  2. Show that data in the multicolumn Listbox
  3. Delete the temp sheet in the Userform unload event

Import the text (Csv) file in the temp sheet

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

And now you can display that data in a multicolumn listbox.

Show that data in the multicolumn Listbox

I am taking an example of 3 Columns and up till tow 20. Change as applicable

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

Delete the temp sheet in the Userform unload event

To Delete the temp sheet, declare the wsTemp on the top of the code so that you can access that in the UserForm_QueryClose event. See this complete example

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!