Subscript out of range when copying worksheet - vba

I would like to create a command button which imports the selected file into the current workbook.
I'm getting Subscript out of range error and I cannot find out the solution.
Here is what I have:
Private Sub CmdBrowseFile_Click()
Dim intChoice, total As Integer
Dim file, ControlFile As String
ControlFile = ActiveWorkbook.Name
'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'Remove all other filters
Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
'Add a custom filter
Call Application.FileDialog(msoFileDialogOpen).Filters.Add( _
"Text Files Only", "*.xlsx")
'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
file = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
'open file
Workbooks.Open fileName:=file
total = Workbooks(ControlFile).Worksheets.Count
Workbooks(file).Worksheets(ActiveSheet.Name).Copy _
after:=Workbooks(ControlFile).Worksheets(total)
Windows(file).Activate
ActiveWorkbook.Close SaveChanges:=False
Windows(ControlFile).Activate
End If

Error :
The error occurs on the line
Workbooks(file).Worksheets(ActiveSheet.Name).Copy... because the Workbooks(<argument>) is expecting just the name of the file, without full path. You are parsing a full path.
Fixed code
Private Sub CmdBrowseFile_Click()
Dim intChoice As Integer, total As Integer 'note the correct declaring, for each variable As Type
Dim strFilePath As String, strControlFile As String
Dim strFileName As String
strControlFile = ActiveWorkbook.Name
'only allow the user to select one strFilePath
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'Remove all other filters
Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
'Add a custom filter
Call Application.FileDialog(msoFileDialogOpen).Filters.Add( _
"Text Files Only", "*.xlsx")
'make the strFilePath dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the strFilePath path selected by the user
strFilePath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
'get the file name
strFileName = Dir(strFilePath)
'open strFilePath
Workbooks.Open fileName:=strFilePath
total = Workbooks(strControlFile).Worksheets.Count
Workbooks(strFileName).Worksheets(ActiveSheet.Name).Copy _
after:=Workbooks(strControlFile).Worksheets(total)
Windows(strFileName).Activate
ActiveWorkbook.Close SaveChanges:=False
Windows(strControlFile).Activate
End If
End Sub
Notes
The main change is the Dim strFileName As String and strFileName = Dir(strFilePath) and it's usage in the code after opening the new book. I changed the variables names for test purposes, I can read it more easily this way. You can use rename tool to revert the changes.

Related

How to activate opened excel in VBA

I have a VBA code that I used to open an excel and do an automatic process. My code is
Dim strPath As String
Dim intChoice As Integer
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
Workbooks.Open Filename:= _
strPath
The process is done here, and this process is navigating between 2 excels, the one that contains the Macro and the one that contains the data. Let's say Excel A and Excel B.
I do the automation in Excel B based on a button in Excel A and then I cut the data from B and add it to A.
Now my problem is that the excels which contains the data are different in names, so I reach to this point in the code:
Windows("EPS.xlsx"). _
Activate
Where I want this "EPS.xlsx" to be replaced by file which was already opened by strPath in the code I wrote in the beginning of this question.
Thank you in advance
Don't think about activating or selecting any workbooks. All you want to do is reference the correct workbook.
Rather than use Workbooks.Open Filename:= strPath which will just open the file, you want to open the file and store a reference to it in a variable. You can then use that variable whenever you want to do something with the workbook.
Sub Test()
Dim wrkBk1 As Workbook
Dim wrkBk2 As Workbook
Set wrkBk1 = Workbooks.Open(Filename:=strPath)
Set wrkBk2 = Workbooks.Open(Filename:=strOtherPath)
wrkBk1.Worksheets("Sheet1").Range("A1") = 5
wrkBk2.Worksheets("Sheet1").Range("A1") = wrkBk1.Worksheets("Sheet1").Range("A1")
wrkBk1.Worksheets("Sheet2").Range("A2").NumberFormat = "#"
wrkBk2.Worksheets("Sheet1").Range("A5").Font.Color = RGB(255, 0, 0)
End Sub
Your code would look something like:
Sub Test2()
Dim strPath As String
Dim intChoice As Integer
Dim wrkBk As Workbook
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
Set wrkBk = Workbooks.Open(Filename:=strPath)
MsgBox wrkBk.Name & " has been opened.", vbOKOnly + vbInformation
End If
End Sub

Vba code to open multiple files in separate sheets of the same workbook

I have a code that allows me to open a file in an excel workbook, however I want to be able to open multiple files within the same workbook named p00001, p00002, p00003 and so on. Does anyone know how I can edit my code to select all the files named this way and open them in separate sheets in the same workbook?
My code is:
Sub Open_Workbook()
Dim my_FileName As Variant
my_FileName = Application.GetOpenFilename
If my_FileName <> False Then
Workbooks.Open Filename:=my_FileName
End If
End Sub
In this solution i used the FileDialog for Selecting Multiple Files.
After that, you need to Loop all thoes Files a for Loop.
Inside the For Loop, you have to Open the File and Import the Sheet. In this Example i Imported all the Sheets the Workbook has.
After the Code is done Importing you close the Source Workbook and do the Same for the Rest of the Files.
Sub Import Files()
Dim sheet As Worksheet
Dim total As Integer
Dim intChoice As Integer
Dim strPath As String
Dim i As Integer
Dim wbNew As Workbook
Dim wbSource As Workbook
Set wbNew = Workbooks.Add
'allow the user to select multiple files
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = True
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
For i = 1 To Application.FileDialog(msoFileDialogOpen).SelectedItems.Count
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(i)
Set wbSource = Workbooks.Open(strPath)
For Each sheet In wbSource.Worksheets
total = wbNew.Worksheets.Count
wbSource.Worksheets(sheet.Name).Copy _
after:=wbNew.Worksheets(total)
Next sheet
wbSource.Close
Next i
End If
End Sub
If you want to get all Files From a Directory you can change the ApplicationFile Dialog with a Loop were you Loop the Directory Like This:
directory = "c:\test\"
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
'Put Code From For Loop here.
Loop

VBA browse file and make operations

Hello I am trying to write a VBA macro, which browses excel files and then makes operation in the files. The code I wrote is as follows:
Option Explicit
Sub SelctFile()
Dim intChoice As Integer
Dim strPath As String
Dim i As Integer
'allow the user to select multiple files
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = True
'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
For i = 1 To Application.FileDialog(msoFileDialogOpen _
).SelectedItems.Count
strPath = Application.FileDialog(msoFileDialogOpen _
).SelectedItems(i)
'print the file path to sheet 1
Cells(i + 1, 2) = strPath
Next i
End If
End Sub
Sub ISIN()
Dim MSReport As Variant
MSReport = Range("B2").Value
Set MSReport = Workbooks.Open(Filename:="MSReport")
Range("W3:W2500").Formula = "=IF(G3="""","""",BDP(G3&"" Equity"",""ID_ISIN""))"
End Sub
The first Sub SelectFile chooses the files and I have the file path in cell B2. So I want to use the path from cell B2 in Sub ISIN.
If I write the address it works, but I want that the macro takes automatically the address.
Also is it possible that the changes are mada without opening the another worksheet.
You should simply use an argument in ISIN, try this! ;)
Option Explicit
Sub SelctFile()
Dim intChoice As Integer
Dim strPath As String
Dim i As Integer
'allow the user to select multiple files
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = True
'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
For i = 1 To Application.FileDialog(msoFileDialogOpen).SelectedItems.Count
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(i)
ISIN strPath
''Add other procedures there!
'NewProcedure strPath
Next i
End If
End Sub
Sub ISIN(ByVal FilePath As String)
Dim MSReport As Excel.Workbook
Set MSReport = Workbooks.Open(Filename:=FilePath)
MSReport.Sheets("SheetName").Range("W3:W2500").Formula = _
"=IF(G3="""","""",BDP(G3&"" Equity"",""ID_ISIN""))"
MSReport.Save
MSReport.Close False
End Sub

Open multiple excel files with user form

Write a code in vba that, Calling user form of one excel file to all the other 10 excel files without having any reference in those 10 excel files.
It is displaying the output in current excel file but not in the destination files and shows the error as Userform is already shown and showing form modally is not possible
Private Sub Workbook_OnClick()
Dim mypath As String
Dim file As Workbook
Dim wb As Workbook
Dim pat As String
Application.ScreenUpdating = False
ChDrive "C:"
ChDir "C:\Users\Administrator\Desktop\John"
'john is a folder on the desktop
mypath = Range("B1").Value
'mypath has the same value as chDir
file = Dir(mypath & "\" & "*.xlsx")
Set wb = Application.Workbooks.Open(file)
If (wb.Click) Then
Application.Visible = False
userform1.Show
End If
End Sub
chDir is mentioned because the default directory shown with the dir() function was C:\Users\Administrator\Documents\ but the folder saved in desktop and that is C:\Users\Administrators\Desktop\John
Sir, It is displaying the run time error - 91 that is "Object variable or with block variable is not set" and highlighting the line "file = Dir(mypath & "\" & "*.xlsx")"
Private Sub Workbook_OnClick()
Dim mypath As String
Dim file As String
Dim wb As Workbook
Dim pat As String
Application.ScreenUpdating = False
ChDrive "C:"
ChDir "C:\Users\Administrator\Desktop\John"
'john is a folder on the desktop
mypath = Range("B1").Value
'mypath has the same value as chDir
file = Dir(mypath & "\" & "*.xlsx")
Do While file <> ""
Set wb = Application.Workbooks.Open(file)
If Not IsEmpty(wb) Then
Application.Visible = False
userform1.Show
End If
wb.Close
file = Dir()
Loop
End Sub

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