Copy Sheet to Another Workbook - Path Error - vba

I am trying to write a code to copy a worksheet, to an open workbook. But I am getting a path error at the end.
The code looks like this right now;
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
YeniStoryBoard.Sheets("Storyboard").Copy After:=ThisWorkbook.Sheets("Kunye") '-> This gives error
YeniStoryBoard.Close
Set YeniStoryBoard_isim = Sheets("Storyboard")
YeniStoryBoard_isim.Name = "StoryboardXXYYZZ"
End With
End Sub
I am going to make some modifications on the code onwards, but this doesn't work properly. :(
Any suggestions?

Here is one-line code to solve your case:
Public Sub TestMe
ThisWorkbook.Worksheets("Storyboard").copy after:= ThisWorkbook.Worksheets("Kunye")
End Sub
It should work. Then start checking what does not work in your case line by line. I guess that the problem is that after Dim YeniStoryBoard As Workbook you do not set it. Thus, it is Nothing.

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

Excel VBA, using FileDialog to open multiple workbooks and reference them

I am currently using to following code to prompt the user for a workbook, open it, get some information from it and then close it. at the moment, I address the opened workbook by using the workbooks collection with and index ("woorkbooks(2)"). Now I need to open two workbooks, and my problem is that I wouldn't know which of the workbooks will be indexed as 2 and which will be indexed as 3. So, I figured there must be a way to get a reference to each workbook.
Function openfile() As Boolean
Dim fd As FileDialog
Dim file_was_chosen As Boolean
Set fd = Application.FileDialog(msoFileDialogOpen)
With fd
.Filters.Clear
.Filters.Add "Excel File", "*.xl*"
End With
file_was_chosen = fd.Show
If Not file_was_chosen Then
MsgBox "You didn't select a file"
openfile = False
Exit Function
End If
fd.Execute
openfile = True
End Function
Now I've seen some solutions to this problem involving getting the full path of each workbook, but I'd prefer avoid using the full path since it contains words in different language (and the name of the workbook appears with question marks). Moreover, I'd prefer a solution in which the user is promped only once for 2 files and not twice.
This version gives the user a single dialog. Enjoy. And whoever downvoted my other answer, please add a comment to that explaining what you so disliked about it that it required a downvote.
Function openfile() As Variant
Dim aOpen(2) As String, itm As Variant, cnt As Long, lAsk As Long
Dim fd As FileDialog
Dim file_was_chosen As Boolean
Set fd = Application.FileDialog(msoFileDialogOpen)
With fd
.Filters.Clear
.Filters.Add "Excel File", "*.xl*"
End With
Do
file_was_chosen = fd.Show
If Not file_was_chosen Or fd.SelectedItems.Count > 2 Then
lAsk = MsgBox("You didn't select one or two files, try again?", vbQuestion + vbYesNo, "File count mismatch")
If lAsk = vbNo Then
openfile = aOpen
Exit Function
End If
End If
Loop While fd.SelectedItems.Count < 1 Or fd.SelectedItems.Count > 2
cnt = 0
For Each itm In fd.SelectedItems
aOpen(cnt) = itm
cnt = cnt + 1
Next
openfile = aOpen
fd.Execute
End Function
Sub test()
Dim vRslt As Variant
Dim wkb As Excel.Workbook, wkb1 As Excel.Workbook, wkb2 As Excel.Workbook
vRslt = openfile
For Each wkb In Application.Workbooks
If wkb.Path & "\" & wkb.Name = vRslt(0) Then Set wkb1 = wkb
If wkb.Path & "\" & wkb.Name = vRslt(1) Then Set wkb2 = wkb
Next
If vRslt(0) = "" Then ' no files
MsgBox "No files opened so nothing happens..."
ElseIf vRslt(1) = "" Then ' one file was opened
MsgBox "One file so do whatever you want for one file"
Else ' two files were opened
MsgBox "Two files so do whatever you want for two files"
End If
End Sub
Working with your existing openfile function, change the return from Boolean to Excel.Workbook. If they don't open a workbook you set it to Nothing instead of false, otherwise you set it to the workbook reference of the file you just opened (You'll need to modify openfile to get that reference). You then just call it twice and set a workbook reference for each call that is not Nothing.
Example code below is written freeform and is untested - it's really just glorified pseudocode - but should point you the right general direction.
sub test
dim lAsk as long
dim wkb1 as excel.workbook
dim wkb2 as excel.workbook
do
if wkb1 is Nothing then
set wkb1 = openfile
if wkb1 is Nothing then
lAsk = msgbox("you didn't select a first file, try again?",vbyesno,"No file selected")
if lAsk = vbNo then exit do
end if
elseif wkb2 is Nothing then
set wkb2 = openfile
if wkb2 is Nothing then
lAsk = msgbox("you didn't select a second file, try again?",vbyesno,"No file selected")
if lAsk = vbNo then exit do
end if
end if
loop while wkb1 is Nothing or wkb2 is Nothing
' do whatever with wkb1 and wkb2 here
end sub
Edited to add:
Here's a very basic shape for your revised openfile function. Again, untested but I've modified it from one of my own procs so it should work
Function openfile() As Excel.Workbook
Dim sFilter As String
Dim sTitle As String
Dim vFileName As Variant
sFilter = "Excel Files (*.xl*), *.xl*, CSV Files (*.csv), *.csv, All Files (*.*), *.*"
sTitle = "Select file to process"
vFileName = Application.GetOpenFilename(filefilter:=sFilter, Title:=sTitle)
If vFileName = False Then
Set openfile = Nothing
Else
Set openfile = Workbooks.Open(Filename:=vFileName)
End If
End Function

Open a workbook using FileDialog and manipulate it in Excel VBA

I am learning how to use Excel macros and I found this code:
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file to kill his non colored cells"
.Filters.Add "Excel", "*.xls"
.Filters.Add "All", "*.*"
If .Show = True Then
txtFileName = .SelectedItems(1)
End If
End With
This code opens the FileDialog. How can I open the selected Excel file without over-writing the previously opened?
Thankyou Frank.i got the idea.
Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Unless I misunderstand your question, you can just open a file read only.
Here is a simply example, without any checks.
To get the file path from the user use this function:
Private Function get_user_specified_filepath() As String
'or use the other code example here.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Please select the file."
get_user_specified_filepath = fd.SelectedItems(1)
End Function
Then just open the file read only and assign it to a variable:
dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

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