User Selection (workbook and sheet name) then Copy and Paste - vba

Is there a way to make it where user selects which sheet to copy from, after they opened file?
I'd like to do this because there may be multiple sheets with same format, but have different names.
Example:
Original workbook named VSC (Contains sheets Compare, Plot)
Secondary workbook named SF (Contains sheets Results1, Results2, Results3)
User clicks button on VSC, and file dialog opens, and user selects SF in a certain directory, then asks user to select which sheet to choose from - user chooses Results2 sheet, copies the data (Range"B2:B5"), then pastes it back to Compare sheet.
Would this be possible? I am not sure how to start.
Current code that asks user to select SF workbook:
Sub GetFilePath()
Dim objFSO as New FileSystemObject
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
FileSelected = .SelectedItems(1)
End With

Here is one approach. You type in the sheet name. Adjust copy and paste ranges to suit.
Sub GetFilePath()
Dim objFSO As New FileSystemObject, w As String, wb As Workbook
Application.ScreenUpdating = False
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
Set wb = Workbooks.Open(.SelectedItems(1))
End With
w = InputBox("Enter sheet name")
If SheetExists(w) Then
wb.Sheets(w).Range("B2:B5").Copy
ThisWorkbook.Sheets("Compare").Range("A1").pastespecial xlvalues
Else
MsgBox "Sheet not found"
End If
wb.Close False
Application.ScreenUpdating = True
End Sub
Function SheetExists(s As String) As Boolean
Dim x
On Error GoTo NextSheet
x = ActiveWorkbook.Sheets(SheetName).Name
SheetExists = True
Exit Function
NextSheet:
SheetExists = False
End Function

Once you have your workbook open, you can enumerate the sheets by name and populate a pick list on a sheet in the VSC workbook...

Here is a different approach to your question. It is using a Timer after opening the new Workbook to ask you every 10 seconds if you are on the sheet you want to copy from. If you answer "Yes" it will copy. If you answer "no" it will restart the 10 second timer.
Sub GetFilePath()
Set MyFile = Application.FileDialog(msoFileDialogOpen)
With MyFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
FileSelected = .SelectedItems(1)
End With
Set newWk = Workbooks.Open(FileSelected, , True)
'Open Selected Workbook and check in 10 seconds for Selected Sheet Name
Application.OnTime Now + TimeValue("00:00:10"), "CheckForSheet"
End Sub
Private Sub CheckForSheet()
Dim SheetName As String
SheetName = ActiveSheet.Name
answer = MsgBox("Is This the Sheet to copy from: " & SheetName & "?", vbYesNo + vbQuestion, "Copy Data?")
If answer = vbYes Then
'ThisWorkbook is the workbook with the Macro/VBA code
'ActiveWorkbook is the workbook where you are selecting the Sheet to copy from
ActiveWorkbook.Sheets(SheetName).Range("B2:B5").Copy
ThisWorkbook.Sheets("Compare").Range("C1:C4").PasteSpecial
Else
'Check Again in 10 Seconds
Application.OnTime Now + TimeValue("00:00:10"), "CheckForSheet"
End If
End Sub

Related

Rename the only worksheet in multiple workbooks in a chosen directory

I am at my wits end and have come to you for your help.
What I am trying to accomplish is to rename a single worksheet (the only worksheet), in multiple workbooks, in a chosen directory to the workbook file name in Excel.
I have found code that will work within a single workbook, however I do not know how to get it to work on multiple workbooks in a directory chosen by the user or ran from a batch/vbs file in the same directory.
Here is the code I was using on a single workbook:
Sub RenameSheet()
Dim wbname
wbname = Replace(ActiveWorkbook.Name, ".xlsx", "")
ActiveSheet.Select
ActiveSheet.Name = wbname
Range("A1").Select
End Sub
I want to be able to do this for all files in a folder chosen by the user or files in the same directory as a batch file/vbs executable file if there is a way to execute this from running either a batch or vbs file?
If there are questions or I have missing something, please let me know and I will answer to the best of my ability.
Any help will be greatly appreciated.
Open File Dialog (Pick which books to modify)
Change sheet name to wbName (your code here)
Close File (Save)
Repeat 2 - 3 for all selected books
This will need modification if there is more than 1 sheet on any of the workbooks selected. IF there is only one sheet, ActiveSheet will suffice.
Sub RenameSheet()
Dim CurrentBook As Workbook
Dim ImportFiles As FileDialog
Dim FileCount As Long 'Count of workbooks selected
Dim wbName As String
'Open File Picker
Set ImportFiles = Application.FileDialog(msoFileDialogOpen)
With ImportFiles
.AllowMultiSelect = True
.Title = "Pick Files to Adjust"
.ButtonName = ""
.Filters.Clear
.Filters.Add ".xlsx files", "*.xlsx"
.Show
End With
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'Cycle through books
For FileCount = 1 To ImportFiles.SelectedItems.Count
Set CurrentBook = Workbooks.Open(ImportFiles.SelectedItems(FileCount))
wbName = Replace(CurrentBook.Name, ".xlsx", "")
CurrentBook.Activate
ActiveSheet.Name = wbName
CurrentBook.Close True
Next FileCount
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
I had to tweak a couple of lines but this works beautifully. Thank you urdearboy.
Sub RenameSheet()
Dim CurrentBook As Workbook
Dim ImportFiles As FileDialog
Dim FileCount As Long 'Count of workbooks selected
Dim wbName As String
'Open File Picker
Set ImportFiles = Application.FileDialog(msoFileDialogOpen)
With ImportFiles
.AllowMultiSelect = True
.Title = "Pick Files to Adjust"
.ButtonName = ""
.Filters.Clear
.Filters.Add ".xlsx files", "*.xlsx"
.Show
End With
Application.DisplayAlerts = False
Application.DisplayAlerts = False
'Cycle through books
For FileCount = 1 To ImportFiles.SelectedItems.Count
Set CurrentBook = Workbooks.Open(ImportFiles.SelectedItems(FileCount))
wbName = Replace(CurrentBook.Name, ".xlsx", "") ' had to rework this line to the original
CurrentBook.Activate
ActiveSheet.Name = wbName
CurrentBook.Close True
Next FileCount ' had to change this to FileCount to remove the error "invalid next control variable"
Application.DisplayAlerts = True
Application.DisplayAlerts = True
End Sub

VBA- working on multiple files

I'm working on a project in which I would like to have: browsing through files and selecting which to work with, copying and opening those workbooks from destination where their copies were created, then creating a new workbook(excel file) and copying information to it, which every workbook opened earlier would be in a separate sheet.
I have already done browsing through the files but I find it hard to go next.
That's the sample code I have by far.
Public Sub CommandButton1_Click()
Dim i As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = True
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "All Files", "*.*"
If .Show = True Then
For i = 1 To fd.SelectedItems.Count
ListBox1.AddItem fd.SelectedItems(i)
Next
End If
End With
End Sub
It's just a matter of iterating through the workbooks.
Dim v as variant
If .Show = True Then
For Each v In fd.SelectedItems
'check if this is a valid workbook
Set WB = Workbooks.Open(v)
'Your code here
WB.Close savechanges:=False
Next v
End If

Prompt user to select a worksheet

I have a Macro, that prompts a user to select an Excel file, like this:
Dim thisBook As Workbook, newBook As Workbook
Dim fd As FileDialog
Dim oFD As Variant
Dim fileName As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.ButtonName = "Select"
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xlsx; *.xls", 1
.Title = "Choose the Report"
.InitialView = msoFileDialogViewDetails
.Show
For Each oFD In .SelectedItems
fileName = oFD
Next oFD
On Error GoTo 0
End With
If fd.SelectedItems.Count = 0 Then
Exit Sub
End If
Set thisBook = ActiveWorkbook
Set newBook = Workbooks.Open(fileName)
This works fine, what I want to do now, and what I failed to find in the internet is the following:
I want to prompt the user to select a worksheet from the newbook, since the sheet name could not be the same in the future.
I came up with this, but I am not very happy with it, since it is rather inconvenient, to let the user type the sheet name:
Function WorksheetExists(WSName As String) As Boolean
On Error Resume Next
WorksheetExists = Worksheets(WSName).Name = WSName
On Error GoTo 0
End Function
Function q() As String
Dim shname As String
Do Until WorksheetExists(shname)
shname = InputBox("Enter sheet name")
If Not WorksheetExists(shname) Then MsgBox shname & " doesn't exist!", vbExclamation
Loop
q = shname
End Sub
Is there a way, to maybe let the user select the sheet name, from all the sheet names? (I am not using an Userform, the Macro starts, if the user clicks a Button)
Make a userform with a blank ListBox and use this code in the userform module
Private Sub UserForm_Initialize()
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Sheets
ListBox1.AddItem sh.Name
Next sh
End Sub
Private Sub ListBox1_Click()
Sheets(ListBox1.Value).Activate
Unload Me
End Sub
Use an InputBox and have the user select any cell inside the desired/target sheet. Setting the type to 8 returns a Range. From this range, you can get the worksheet then its name.
Dim desiredSheetName as String
desiredSheetName = Application.InputBox("Select any cell inside the target sheet: ", "Prompt for selecting target sheet name", Type:=8).Worksheet.Name
Debug.Print desiredSheetName

VBA Opening workbook error

I have a VB form in Access 2010, that opens a file dialog box to make a excel selection. I send the file path as string to my variable: directory (directory = strPath) to open the workbook and copy its contents to my current workbook. Which works fine if you intend to use the tool once. It's when you import one file, then another that's in the same directory the error occurs.
Non-working Example:
Selected C:\Desktop\File1.xls, Import
Selected C:\Desktop\File2.xls, Import
Error:
Run-time error '1004':
A document with the name 'Tool.xlsm' is already open. You cannot open two documents with the same name, even if the documents are in different folders. To open the second document, either close the document that's currently open, or rename one of the documents.
Working Example (Separate Folders):
Selected C:\Desktop\File1.xls, Import
Selected C:\Desktop\TestFolder\File2.xls, Import
Public Sub CommandButton1_Click()
Dim intChoice As Integer
Dim strPath As String
Application.EnableCancelKey = xlDisabled
'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
'print the file path to sheet 1
TextBox1 = strPath
End If
End Sub
Public Sub CommandButton2_Click()
Dim directory As String, FileName As String, sheet As Worksheet, total As Integer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
directory = strPath
FileName = Dir(directory & "*.xls")
Do While FileName <> ""
Workbooks.Open (directory & FileName)
For Each sheet In Workbooks(FileName).Worksheets
total = Workbooks("Tool.xlsm").Worksheets.Count
Workbooks(FileName).Worksheets(sheet.name).Copy _
after:=Workbooks("Tool.xlsm").Worksheets(total)
Next sheet
Workbooks(FileName).Close
FileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableCancelKey = xlDisabled
Application.DisplayAlerts = False
End Sub
In DEBUG mode it doesn't like
Workbooks.Open (directory & FileName)
Any suggestions on a way to eliminate this error?
First, between directory and FileName, i assume there is a "\".
secondly, simply check if the workbook is already opened:
dim wb as workbook
err.clear
on error resume next
set wb = Workbooks (FileName) 'assuming the "\" is not in FileName
if err<>0 or Wb is nothing then 'either one works , you dont need to test both
err.clear
set wb= Workbooks.Open (directory & FileName)
end if
on error goto 0
if you don't use application.enableevents=false, your opened Wb will trigger its workbook_open events !
I wanted to post the working code, maybe it will help someone in the future. Thanks again to those who left comments.
This code will open a file dialog, allow the user to select 1 excel file then copy all sheets from the selected file into the current workbook.
Public Sub CommandButton1_Click()
Dim intChoice As Integer
Application.EnableCancelKey = xlDisabled
'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
'print the file path to textbox1
TextBox1 = strPath
End If
End Sub
Public Sub CommandButton2_Click()
Dim directory As String, FileName As String, sheet As Worksheet, total As Integer
Dim wb As Workbook
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Err.Clear
On Error Resume Next
Set wb = Workbooks(FileName) 'assuming the "\" is not in FileName
If Err <> 0 Or wb Is Nothing Then 'either one works , you dont need to test both
Err.Clear
Set wb = Workbooks.Open(directory & TextBox1)
End If
On Error GoTo 0
FileName = Dir(directory & TextBox1)
Do While FileName <> ""
Workbooks.Open (directory & TextBox1)
For Each sheet In Workbooks(FileName).Worksheets
total = Workbooks("NAMEOFYOURWORKBOOK.xlsm").Worksheets.Count
Workbooks(FileName).Worksheets(sheet.name).Copy _
after:=Workbooks("NAMEOFYOURWORKBOOK.xlsm").Worksheets(total)
Next sheet
Workbooks(FileName).Close
FileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableCancelKey = xlDisabled
Application.DisplayAlerts = False
End Sub

Excel User forms in vba

I'm developing VBA code using Forms. I have a certain button option to let the user select the workbook using FileDialog. The workbook file may contain 4 or 5 sheets itself. I have combobox with empty.
I need to have the sheetnames of the user selected workbook listed in the combobox automaticaly without opening the workbook.
I tried with the following code, but got the names of already opened workbooks.
Private Sub CommandButton2_Click()
Set myfile = Application.FileDialog(msoFileDialogOpen)
With myfile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
Fileselected = .SelectedItems(1)
End With
With Fileselected
For i = 1 To Sheets.Count
ComboBox2.AddItem Sheets(i).Name
Next i
End With
At the moment Sheets refers to the current workbook as you do nothing with Fileselected.
You must open the selected file, otherwise how can you examine its contents?
Set myfile = Application.FileDialog(msoFileDialogOpen)
With myfile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
Fileselected = .SelectedItems(1)
End With
Dim doc As Workbook
Set doc = Application.Workbooks.Open(Fileselected)
With doc
For i = 1 To .Sheets.Count
ComboBox2.AddItem .Sheets(i).Name
Next i
.Close
End With