Reference to a workbook selected with filedialog in vba - vba

I am trying to create a sort of user interface in Excel and need to find a simple solution to copy a worksheet from a selected workbook to a specific workbook. So far I've written the code below but I don't know how to reference the selected workbook in code.
Users are going to need to copy the worksheet ( it's called Storyboard and name never changes ) from many different workbooks ( with different names ) to the workbook with the VBA.
Right now another workbook can be selected, but I cannot refer to that workbook in the codes.
Also, there are some macros on the workbooks that users going to select, how can I disable them after opening?
Here is the code so far;
Sub Storyboard_Ekle()
Dim DosyaSec As Office.FileDialog
Set DosyaSec = Application.FileDialog(msoFileDialogFilePicker)
With DosyaSec
.AllowMultiSelect = False
.Title = "Lütfen yeni eklenecek Storyboard dosyasini seçiniz."
.Filters.Clear
.Filters.Add "Excel Macro-Enabled Workbook", "*.xlsm"
.Filters.Add "Excel Workbook", "*.xlsx"
.Filters.Add "All Files", "*.*"
If .Show = True Then
YeniSB = .SelectedItems(1)
End If
Dim YeniStoryBoard As Workbook
Dim AnaDosya As Workbook
Dim YeniStoryBoard_Sheet As Worksheet
Dim AnaDosya_Sheet As Worksheet
Application.ScreenUpdating = False
Set AnaDosya = ThisWorkbook
Application.EnableEvents = False
Set YeniStoryBoard = Workbooks.Open(YeniSB)
YeniStoryBoard.Worksheets("Storyboard").Copy After:=ThisWorkbook.Worksheets("Kunye")
YeniStoryBoard.Close
Set YeniStoryBoard_isim = Sheets("Storyboard")
YeniStoryBoard_isim.Name = "StoryboardXXYYZZ"
Application.EnableEvents = True
End With
End Sub
Thank you so much. :)

I think you should using this solution to disable them after opening
Application.EnableEvents = False 'disable Events
Set YeniStoryBoard = Workbooks.Open(YeniSB) 'open workbook
Application.EnableEvents = True 'enable Events
To ensure disable event of workbook, You can use additional statements
YeniStoryBoard.Application.EnableEvents = False
'Do something
YeniStoryBoard.Application.EnableEvents = True
YeniStoryBoard.Close

Related

Excel VBA code: Having troubles opening new workbook, copying range to original workbook

Good morning-
I've managed to piece together a code that will, from my original workbook, open a new workbook, copy a specific range and paste that range back to the original workbook and close the referenced workbook. I've tested each section of my code, and it seems to work perfectly until I run the entire code together.
Now I continuously get a
'subscript out of range'
error, that no matter what I try to modify, will not go away. I've researched as much as I can to try to figure out the differences.
As always, thank you to the StackOverflow users that help me always workout my issues!
Sub import()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set y = ThisWorkbook
With Application.FileDialog(msoFileDialogOpen)
.Filters.Clear
.Filters.Add "Excel 2007-13", "*.xlsx"
.AllowMultiSelect = False
.Show
End With
Set x = ActiveWorkbook
'##Now, copy what you want from x:
x.Sheets("QBEPaymentAdvice").Range("D13", "T60").Copy
'##Now, paste to y worksheet:
y.Sheets("QBE").Range("A1").PasteSpecial
'##Close Workbook x
x.Close
End Sub
Try this way :
Sub import()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set y = ThisWorkbook
With Application.FileDialog(msoFileDialogOpen)
.Filters.Clear
.Filters.Add "Excel 2007-13", "*.xlsx"
.AllowMultiSelect = False
If .Show Then
xlFileName = .SelectedItems(1)
Else
'if user pressed CANCEL - exit sub
MsgBox "User pressed CANCEL"
Exit Sub
End If
End With
Set x = Workbooks.Open(xlFileName)
'##Now, copy what you want from x:
x.Sheets("QBEPaymentAdvice").Range("D13", "T60").Copy
'##Now, paste to y worksheet:
y.Sheets("QBE").Range("A1").PasteSpecial
'##Close Workbook x
x.Close
End Sub

“This operation requires the merged cells to be identically sized.” when copying a range VBA

I have code that copies a range from a sheet in one workbook and pastes it in a sheet in another workbook. The range includes merged cells (I didn't design it). The range it pastes the data is formatted exactly the same as where it is copied from. I tested the VBA by copying it to blank workbooks, and it works. However, when I try to copy it to a the worksheet that already has that same formatting, it gives the “This operation requires the merged cells to be identically sized.” error, and I'm unsure how to get around this. Here is what I have:
Sub testcopying()
Dim FileNm As Object, Cnt As Integer
Dim TargetFiles As FileDialog
Set TargetFiles = Application.FileDialog(msoFileDialogOpen)
With TargetFiles
.AllowMultiSelect = True
.Title = "Multi-select target data files:"
.ButtonName = ""
.Filters.Clear
.Filters.Add "*.xls* files", "*.xls*"
.Show
End With
If TargetFiles.SelectedItems.Count = 0 Then
MsgBox "PICK A FILE!"
Exit Sub
End If
'On Error GoTo below
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Cnt = 1 To TargetFiles.SelectedItems.Count
'open the file and assign the workbook/worksheet
Set FileNm = Workbooks.Open(TargetFiles.SelectedItems(Cnt))
ThisWorkbook.Sheets("Vendor Data Sheets").Range("A1:AJ191").Copy
Workbooks(FileNm.Name).Sheets("Sheet1").Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
Workbooks(FileNm.Name).Close SaveChanges:=True
Next Cnt
below:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
If Err.Number <> 0 Then MsgBox "File Error"
End Sub
Any thoughts? I think I may have to write it so it unmerges every cell before pasting the data, then re-merges it, as it was able to successfully paste in the blank workbook (with no merging). But with hundreds of different merged cells, that would take a bit to type up, so I'm hoping there are easier answers. Thanks.
The problem is here xlPasteValues- you cannot paste only values because you are copying also formats (merged cells)
If it's not essential for you to keep the formatting ( as you said those are the same in all workbooks) you can just remove xlPasteValues from your code.
Reason #1 of many: It is very possible you accidentally have selected two worksheets before making the change as I have done in my case.

How to open document from Macro without Activating

I've been working on a macro where at one point I need to open a document, copy and edit some data, and then return to the previous document to continue with the Macro. I have a fileDialog that I run to let the user choose the document, but the problem is that this then activates the document, causing the screen to flash even with ScreenUpdating off. Is there an alternative to Workbooks.Open I can use that won't activate the new document? A setting in Workbooks.Open I can change to prevent it from activating? A way to stop the screen from flashing upon the document activating? Here is the code for the fileDialog and a few lines on each side:
Set fileDialog = Application.fileDialog(msoFileDialogFilePicker)
Application.ScreenUpdating = False
With fileDialog
.InitialFileName = "C:\Users\User\Documents"
.AllowMultiSelect = False
.Filters.Clear
.Title = dialogTitle
If .Show = False Then
Application.ScreenUpdating = True
MsgBox "No file chosen. Click Import Contact List to try again."
Exit Sub
End If
strPathFile = .SelectedItems(1)
End With
Set wbSource = Workbooks.Open(Filename:=strPathFile)
Any solution would be greatly appreciated.
My assumption is that you want to let the user open a file, leave it open, but make your workbook active afterwards so the opened file remains "in the background" for the user to navigate to later on. You've noticed some annoying flicker and came here for answers.
The only way I could reproduce the behavior you describe, with code similar to yours, is when I opened a file that was already opened in the same Excel session (see 3rd use case below). Notice that your code doesn't close the just opened workbook, so the first time you run it, you're in use case 2 below, and the second time you run it, you're in use case 3 below.
If, however, you can close the workbook at the end of your process, you'll be in the 1st use case below and all should be fine.
Let's see if anybody can come up with solutions to use cases 2 and 3.
This first use case typically doesn't introduce flicker:
Application.ScreenUpdating = False
Application.EnableEvents = False 'For good measure.
Set myWb = Application.Workbooks.Open("... path of some workbook that's not already open ...")
'... Do stuff ...
myWb.Close
Application.EnableEvents = True
Application.ScreenUpdating = True
I can't make the other 2 use cases below behave as desired.
Second use case is when the workbook must be left opened at the end of the process described above, but not active, all without any flickering. Whatever I've tried, the opened workbook becomes the active one upon leaving the code:
Application.ScreenUpdating = False
Application.EnableEvents = False 'For good measure.
Set myWb = Application.Workbooks.Open("... path of some workbook that's not already open ...")
'... Do stuff ...
'myWb.Close 'Here, the workbook is left opened.
ThisWorkbook.Activate 'Trying...
Application.EnableEvents = True
Application.ScreenUpdating = True
ThisWorkbook.Activate 'Trying harder...
'Be my guest...
'Note: Application.OnTime eventually calling ThisWorkbook.Activate doesn't count!
Third use case is an oddity and probably what happens to OP. Take the second use case above but open a workbook that's already opened in the same Excel instance. After a flicker even though ScreenUpdating = False during the operations (not cool), the code will leave with ThisWorkbook as the active one (cool!) .
I've tried playing with myWb.Windows(1).Visible = False, DoEvents, you name it, to no avail. Your comments are welcome.
EDIT (3 years later)
A dirty workaround is to open the workbook, then immediately set its IsAddin property to True. This will remove it from Excel's UI and leave the workbook with executing code at the front, no matter what. The caveat is you now have to manage the opened workbook's visibility (e.g. setting IsAddin = False when the user wishes to see it) and lifetime (e.g. closing it when exiting your application's workbook). But it's doable.
On opening a workbook, you can hide the workbook or activate ThisWorkbook in order no to show the just opened workbook.
Sub OpenAndHide()
Dim wbSource As Workbook
Dim FileDialog As FileDialog
Dim dialogTitle As String
Dim strPathFile As String
Set FileDialog = Application.FileDialog(msoFileDialogFilePicker)
dialogTitle = "Open And Hide"
With FileDialog
.InitialFileName = "C:\Users\User\Documents"
.AllowMultiSelect = False
.Filters.Clear
.Title = dialogTitle
If .Show = False Then
Application.ScreenUpdating = True
MsgBox "No file chosen. Click Import Contact List to try again."
Exit Sub
End If
strPathFile = .SelectedItems(1)
End With
Set wbSource = Workbooks.Open(Filename:=strPathFile)
ThisWorkbook.Activate
'// Hide the workbook
'strPathFile = GetFilenameFromPath(strPathFile)
'Windows(strPathFile).Visible = False
End Sub
Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost '\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
You can try
Set wbSource = Workbooks.Open(Filename:=strPathFile)
Workbooks(name of users workbook).Activate
or
Set wbSource = Workbooks.Add(trPathFile)
Hope it helps.

How to saveas a specific spreadsheets in a workbook with multiples spreadsheets

I have one workbook with multiples spreadsheets and multiples macros assigned to buttons. Well, one of these buttons is responsible to create a new spreadsheets named "Savings" and saveas this spreadsheets with the suggested name "savings". I would like that when runs the macro pops-up the saveas window and the Field Name suggests "Savings.xlsm". My code to create the "Savings" spreadsheets is working really fine but the Save file is not working, could you guys help me?
Private Sub Relatorio_Saving_Click()
'Code to create the worksheet named "Savings"
Application.ScreenUpdating = False
Dim ws As Worksheet
With ThisWorkbook
For Each ws In .Worksheets
If ws.Name = "Savings" Then 'If Savings exists
Application.DisplayAlerts = False 'Disable warnings
ws.Delete 'Delete Worksheet
Application.DisplayAlerts = True 'Enable warnings
Exit For
End If
Next ws
'Add Savings Worksheet
Set ws = .Worksheets.Add(After:=.Worksheets(.Worksheets.count))
ws.Name = "Savings"
End With
After that there is a lot of codes that work on this worksheet Savings that is not useful for the main purpose.
On the end I have the saveas code, that is not working like I want to:
With Application.FileDialog(msoFileDialogSaveAs) 'SaveAs Dialog
.InitialFileName = "Savings.xlsm" 'Suggested Name
.AllowMultiSelect = False
.Show
If .SelectedItems.count > 0 Then
ThisWorkbook.SaveAs .SelectedItems(1) 'Save File
End If
End With
This code is saving as the whole Workbook, What I want is just to save as the spreadsheets named Savings, and when pops-up the saveas dialog window I want the Save-Astype file shows .xlsm

Run the same VBA macro on different excel files with a button on my custom Ribbon

I've created a VBA macro and need to perform the same tasks on multiple different files. Ideally i'd like to create a button on my Ribbon and execute the tasks with the click of a button. How do I make the macro available to multiple files and execute the tasks using the data from a newly opened worksheet? I've added the macro to a PERSONALS.xlsb file and can see the macro available every time I open Excel, but the macro only executes the tasks on the PERSONALS.xlsb file, not the newly opened file.
Sub Export_Files()
Dim sExportFolder, sFN
Dim rDiscription As Range
Dim rHTMLcode As Range
Dim oSh As Worksheet
Dim oFS As Object
Dim oTxt As Object
'sExportFolder = path to the folder you want to export to
'oSh = The sheet where your data is stored
sExportFolder = "C:\Users\bhinton\Desktop\ActionTags"
Set oSh = Sheet1
Set oFS = CreateObject("Scripting.Filesystemobject")
For Each rDiscription In oSh.UsedRange.Columns("C").Cells
Set rHTMLcode = rDiscription.Offset(, 6)
'Add .txt to the article name as a file name
sFN = rDiscription.Value & ".html"
Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & sFN, 2, True)
oTxt.Write rHTMLcode.Value
oTxt.Close
Next
End Sub
Instead of
Set oSh = Sheet1
You need to use
Set oSh = ActiveSheet
Using ActiveSheet means that the code will use the newly opened workbook and the active sheet which I think is what you want.
Or if you always want Sheet1 of the currently active workbook, you can do this:
Set oSh = ActiveWorkbook.Worksheets("Sheet1")
Here's one way to prompt the user to select files then iterate through them:
Option Explicit
Sub OpenFilesAndIterate()
Dim DataDialog As FileDialog
Dim NumFiles As Long, Counter As Long
Dim MyWorkbook As Workbook
Dim MySheet As Worksheet
'prompt the user to select data files
Set DataDialog = Application.FileDialog(msoFileDialogOpen)
With DataDialog
.AllowMultiSelect = True
.Title = "Please pick the files you'd like to operate on:"
.ButtonName = ""
.Filters.Clear
.Filters.Add ".xlsx files", "*.xlsx"
.Show
End With
'assign the number of files selected for an easy loop boundary
NumFiles = DataDialog.SelectedItems.Count
'check to see if the user clicked cancel
If NumFiles = 0 Then Exit Sub
'Start looping through and do work
For Counter = 1 To NumFiles
Set MyWorkbook = Workbooks.Open(DataDialog.SelectedItems(Counter))
Set MySheet = MyWorkbook.Worksheets("Sheet1")
'
'insert your code to operate on worksheet here
'
MyWorkbook.Save
MyWorkbook.Close SaveChanges:=False
Next Counter
End Sub
In the options for Excel, click on Customize Ribbon. Above the list of things you can add there should be a dropdown box where you can select Macros. The list should then be populated with macros to add to your ribbon!