How To Display Part of Excel on VBA Form - excel

I have a file on .csv format and from A-S columns, it has some records like a table. My complete program will insert/remove/delete/add some rows, columns and editing cell values etc. I managed to code all the operations that i need, now i'm trying to integrate it with a gui.
What I want is to display cells from Ax1 to the last column that has record on VBA user form. How can i do that?
*ps: again, my file's format is .csv and I am using Excel 2007

You can use a multi column Listbox to show the data.
LOGIC
Import the text (Csv) file in the temp sheet
Show that data in the multicolumn Listbox
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

Related

Combine sheets from different workbooks with same name

I'm trying to solve an issue i'm currently dealing with.
Below you'll find the issue:
I'm having multiple excel sheets that I'd like to merge into one file (located into different workbooks).
Each workbook consists out of the same sheets (SHEET1, SHEET2, SHEET3).
I'd like to merge all workbooks into 1 masterfile - and want to keep the same structure (SHEET1 = all date form all sheets).
So far I've manged to solve the merging issue with the below code:
Sub mergeFiles()
Dim numberOfFilesChosen, i As Integer
Dim tempFileDialog As FileDialog
Dim mainWorkbook, sourceWorkbook As Workbook
Dim tempWorkSheet As Worksheet
Set mainWorkbook = Application.ActiveWorkbook
Set tempFileDialog = Application.FileDialog(msoFileDialogFilePicker)
tempFileDialog.AllowMultiSelect = True
numberOfFilesChosen = tempFileDialog.Show
For i = 1 To tempFileDialog.SelectedItems.Count
Workbooks.Open tempFileDialog.SelectedItems(i)
Set sourceWorkbook = ActiveWorkbook
For Each tempWorkSheet In sourceWorkbook.Worksheets
tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
Next tempWorkSheet
sourceWorkbook.Close
Next i
End Sub
I navigate via de Application.FileDialog to the folder with the different sheets. I select the files i want to merge, and then VBA does its job, and merges the files into one Excel sheet.
Hence some of the sheets are having the same name (=always) = SHEET 1, SHEET 2, SHEET 3, the merged sheets are having the same name with a figure behind (= SHEET1 (1), SHEET1 (2) ...)
I've managed to merge all the sheets into one worksheet, using the below code - but i can't mange to add a restriction to it - e.g. merge all the sheets starting with (SHEET1* into MASTERDATA SHEET1, SHEET2 * into MASTERDATA SHEET2, SHEET3 * into MASTERDATA SHEET3)
Sub Merge_Sheets()
Sheets.Add
ActiveSheet.Name = "MASTERDATA"
For Each ws In Worksheets
ws.Activate
If ws.Name <> "MASTERDATA" Then
ws.UsedRange.Select
Selection.Copy
Sheets("MASTERDATA").Activate
ActiveSheet.Range("A1048576").Select
Selection.End(xlUp).Select
If ActiveCell.Address <> "$A$1" Then
ActiveCell.Offset(1, 0).Select
End If
ActiveSheet.Paste
End If
Next
End Sub
Could any of you help me out + explain briefly the next step?
Kind Regards
D
You should check if the sheet name already exists in mainWorkbook. If it does append that data to the end of that sheet rather than insert a new worksheet. Therefore, you do not need to the second code
Try this (not tested and you might need to debug it, also note comments starting with '*)
Sub mergeFiles()
'* declare the type for each variable (no just at the end of the line)
'* always use Long if you're tempted to use Integer
Dim numberOfFilesChosen As Long, i As Long
Dim tempFileDialog As FileDialog
Dim mainWorkbook As Workbook, sourceWorkbook As Workbook
Dim tempWorkSheet As Worksheet
'* declare the destination sheet
Dim destWorkSheet As Worksheet
Set mainWorkbook = ThisWorkbook ' Application.ActiveWorkbook
Set tempFileDialog = Application.FileDialog(msoFileDialogFilePicker)
tempFileDialog.AllowMultiSelect = True
numberOfFilesChosen = tempFileDialog.Show
For i = 1 To tempFileDialog.SelectedItems.Count
'* you can set sourceWorkbook directly here
Set sourceWorkbook = Workbooks.Open(tempFileDialog.SelectedItems(i))
'Set sourceWorkbook = ActiveWorkbook
On Error Resume Next
For Each tempWorkSheet In sourceWorkbook.Worksheets
Set destWorkSheet = mainWorkbook.Sheets(tempWorkSheet.Name)
If Err.Number > 0 Then '* worksheet doesn't exist in mainWorkbook
tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
Err.Clear
Else '* worksheet already exists
With tempWorkSheet.UsedRange
.Copy Destination:=destWorkSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1)
'* If you only want to copy the values remove the above line and uncomment the below line
'destWorkSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1).Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
End If
Next tempWorkSheet
On Error GoTo 0
sourceWorkbook.Close
Next i
End Sub

Deleting sheet in Excel 365

I have below VBA code:
Sub abc()
Dim wb As Workbook
Set wb = Workbooks("Book1.xlsx")
wb.Sheets("sheet1").Activate
On Error Resume Next
wb.Sheets("Sheet2").Delete
wb.Sheets("Sheet3").Delete
End Sub
I have 1 blank Excel file (Book1.xlsx) with 2 sheets (sheet1 and sheet2).
In Excel 2013 it works.
The same code in Excel 365 is throwing error message
Run time error 9: subscript out of range
Option Explicit
Sub abc()
Dim wb As Workbook
Set wb = Workbooks("Frou Frou.xlsx") '<- Check if the workbook has the correct name.
With wb
Application.DisplayAlerts = False '<- Remove alerts asking for confirmation of deleting the sheet
.Sheets("Sheet2").Delete '<- Check if the both sheets appear in the workbook.
.Sheets("Sheet3").Delete
Application.DisplayAlerts = True '<- Remove alerts
End With
End Sub
Sub deleteSelectedSheets()
Dim wb As Workbook
Dim sht As Worksheet
Set wb = Workbooks("Your.xlsx")
For Each sht In wb.Worksheets
Select Case sht.name
Case Is = "Sheet1" ' You can add as many case as you want
sht.Delete
Case Is = "Sheet2"
sht.Delete
Case Else
' Do nothing
End Select
Next sht
End Sub

Excel-VBA Copy data from one worksheet to another worksheet and paste in new row

I am new to VBA. And below is my code.What i am trying to do is copy data from one worksheet and paste it in another worksheet. The only problem with my code is that every time i try to copy a new file it overwrites the previous data . What i want is to paste data in new line.
Private Sub CommandButton1_Click()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sheet As Worksheet
Dim PasteStart As Range
Dim erow
Set wb1 = ActiveWorkbook
Set PasteStart = [Dominoes_Excel!A1]
FileToOpen = Application.GetOpenFilename
If FileToOpen = False Then
MsgBox ("No File Specified.")
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
For Each Sheet In wb2.Sheets
With Sheet.UsedRange
.Copy PasteStart
Set PasteStart = PasteStart.Offset(.Rows.Count)
End With
Next Sheet
End If
wb2.Close
End Sub
The next line down is given by
Set PasteStart = PasteStart.Offset(1,0) '1 row down, no columns
The next blank line in a sheet (which I suspect is what you want) is given by
set pastestart = worksheets("Dominoes_Excel").cells(worksheets("Dominoes_Excel").rows.count,1).end(xlup).offset(1,0)

Copy data from current workbook and paste it to another open workbook with userform list

I am wanting to have a button open a userform with a list of all open Workbooks. The user selects the workbook they want and the code copies data from a fixed range in the current workbook and pastes it into a fixed range in the user selected workbook.
While searching around I found this code, that works similarly but copies from the selected workbook and pastes into the current one.
Option Explicit
Const PSWD = "atari"
Private Sub CancelButton_Click()
Unload Me
End Sub
Private Sub CopyPasteButton_Click()
ActiveSheet.Unprotect Password:=PSWD
'This code will be executed when the "Copy" button is clicked on the userform.
Dim wsData As Worksheet
Dim rCopy As Range
Dim CopyRw As Long
Set wsData = ThisWorkbook.Sheets("SALES Details")
With Application
.DisplayAlerts = False
.ScreenUpdating = True
With wsData
.Unprotect PSWD
CopyRw = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
End With
On Error GoTo exit_err
With Workbooks(Me.ListBox1.Value).Sheets("Master Sheet")
Set rCopy = .Cells(10, 1).CurrentRegion
Set rCopy = rCopy.Offset(1, 0).Resize(rCopy.Rows.Count - 1, 40)
rCopy.Copy ThisWorkbook.Sheets("SALES Details").Cells(CopyRw, 1)
End With
Unload Me
exit_err:
wsData.Protect Password:=PSWD
.DisplayAlerts = True
.ScreenUpdating = True
.CutCopyMode = False
End With
End Sub
Private Sub UserForm_Activate()
'Populate list box with names of open workbooks, excluding main workbook.
Dim wb As Workbook
For Each wb In Workbooks
If wb.Name <> ThisWorkbook.Name Then ListBox1.AddItem wb.Name
Next wb
End Sub
This code works great, for what it does. I have been trying to edit it without luck. How can I edit this to reverse the direction and have it copy from a fixed range in the current sheet (A50:J57) to a fixed range on the user selected sheet (A4:J11)?
I think this should work. Of course you have to adapt the sheet names in code.
Private Sub CopyPasteButton_Click()
Dim mySheet As Worksheet, otherSheet As Worksheet
On Error GoTo exit_err
Application.DisplayAlerts = False
Set mySheet = ThisWorkbook.Sheets("SheetXYZ")
Set otherSheet = Workbooks(Me.ListBox1.Value).Sheets("SheetABC")
mySheet.Range("A50:J57").Copy Destination:=otherSheet.Range("A4:J11")
exit_err:
Application.DisplayAlerts = True
End Sub
UPDATE
For copying the values and not the formulas of the range use this code instead of the Copy function:
mySheet.Range("A50:J57").Copy
otherSheet.Range("A4:J11").PasteSpecial xlPasteValuesAndNumberFormats
For further options of the PasteSpecial function see the documentation.

Copying only the visible cells from visible worksheets into a new workbook, excel 2007 VBA

I have a master spreadsheet Master Spreadsheet.xlsm and I want to use it to create another spreadsheet defined by OutputFN.
This second spreadsheet needs to be a copy of the first but only containing the visible cells from visible worksheets in the first.
I have found code to copy just the visible sheets and other code to copy just the visible cells but not the two together. Any help would be much appreciated.
This is what I've got so far:
Private Sub saveone()
Dim OutputFN As String
Dim OutputWB As Workbook
Dim SourceWB As Workbook
Dim i As Integer
i = 1
Set SourceWB = Application.ActiveWorkbook
OutputFN = ThisWorkbook.Worksheets("Setup Page").Range("B12").Value
Set OutputWB = Workbooks.Add
'Selects active (not hidden cells) from visible sheets and copies
For Each Sheet In ThisWorkbook.Sheets
If Sheet.Visible = True Then
ThisWorkbook.ActiveSheet.Cells. _
SpecialCells(xlCellTypeVisible).Copy
'Pastes into new workbook
Worksheets(i).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues
Selection.PasteSpecial Paste:=xlPasteFormats
'Saves new file as output filename in the directory created earlier
ActiveWorkbook.SaveAs (OutputFN)
i = i + 1
End If
Next
End Sub
Something like this
I've tidied up the variables and tweaked the logic a little as well
Private Sub saveone()
Dim OutputFN As String
Dim OutputWB As Workbook
Dim SourceWB As Workbook
Dim ws As Worksheet
Dim ws2 As Worksheet
Set SourceWB = ThisWorkbook
OutputFN = SourceWB.Worksheets("Setup Page").Range("B12").Value
Set OutputWB = Workbooks.Add(1)
Application.ScreenUpdating = False
For Each ws In SourceWB.Sheets
If ws.Visible Then
Set ws2 = OutputWB.Sheets.Add(After:=OutputWB.Sheets(OutputWB.Sheets.Count))
ws.Cells.SpecialCells(xlCellTypeVisible).Copy
ws2.[a1].PasteSpecial xlPasteValues
ws2.[a1].PasteSpecial xlPasteFormats
End If
Next
Application.ScreenUpdating = True
ActiveWorkbook.SaveAs (OutputFN)
End Sub

Resources