Error importing sheets in VBA - vba

I'm trying to write a VBA macro to import a sheet from another workbook. I get a "subscript out of range" error on the "copy" line. The file opens correctly, but I'm not sure what goes wrong after that.
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim lastdate As String, filename As String
lastdate = Format(sheet_1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"
Workbooks.Open (filename)
Workbooks(filename).Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
Workbooks(filename).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = False
End Sub
Edit: error changed to "subscript out of range", code changed so worksheets referenced by index.
Code v2:
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim lastdate As String, filename As String
lastdate = Format(sheet1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"
Dim wbk As Workbook
wbk = Workbooks.Open(filename)
wbk.Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
wbk.Close
End Sub

You get the subscript out of range error because you don't have the workbook's Name right. The Name isn't the same thing as the full path (which is what you have been assuming); it's the same thing as the filename.
This will work:
Workbooks.Open "C:\Dir\file1234.xlsm"
Workbooks("file1234.xlsm").Sheets(1).Range("a1").Value = "yay"
Whereas this won't:
Workbooks.Open "C:\Dir\file1234.xlsm"
Workbooks("C:\Dir\file1234.xlsm").Sheets(1).Range("a1").Value = "yay"
But a much better way to reference a workbook is to set an explicit reference to it like this:
Dim wbk As Workbook
Set wbk = Workbooks.Open(filename)
wbk.Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
With wbk you now have a handle on the workbook you want; you don't have to guess its name or anything.

The keyword 'Set' is required when referencing an object variable:
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
'Application.DisplayAlerts = False '<<this does not look like it is required - when is an alert displayed in the method?
Dim lastdate As String, filename As String
lastdate = Format(sheet1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"
Dim wbk As Workbook
Set wbk = Workbooks.Open(filename) '<<Set is required
wbk.Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
wbk.Close
End Sub

Option Explicit
Sub Import_Worksheets()
Dim FolderPath As String
Dim Filename As String
Dim sheet As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
FolderPath = "H:G:\D S Class\Excel VBA (Macro)\RTO form\VBA\"
Filename = Dir(FolderPath & "RESTAURANT_USAGE_DATA.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each sheet In ActiveWorkbook.Sheets
sheet.Copy After:=ThisWorkbook.Sheets(1)
Next sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
enter code here

Related

VBA code has Runtime Error with XLSM documents but not XLS

This VBA code is working for me in copying and moving XLS files but when I try to run it on an XLSM file it is telling me runtime error and is highlighting;
"CurrentWB.Sheets(SheetNumber).Select 'Selects All Worksheets in Workbook"
Run-Time Error 1004: Select Method of Worksheet Class Failed
Does anyone know what the issue might be?
Sub AutoUpdate()
On Error Resume Next
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.PrintCommunication = False
Dim SystemPath As String
Dim FilePath As String
Dim FileName As String
Dim UtilityType As String
Dim ThisName As String
Dim FlattenedFilePath As String
Dim FlattenedFileFolder As String
Dim CurrentWB As Workbook 'Workbook Stores Workbook
SystemPath = Range("Sys.Path")
UtilityType = Range("Utility.Type")
FlattenedFileFolder = Range("Flattened.Files")
FilePath = SystemPath & UtilityType
FileName = Dir(FilePath & "\*.xls")
FlattenedFilePath = FilePath & "\" & FlattenedFileFolder
Do While FileName <> ""
Set CurrentWB = Workbooks.Open(FileName:=FilePath & "\" & FileName, UpdateLinks:=3) 'Sets CurrentWB = to that long name. This becomes the name of the workbook.
CurrentWB.RunAutoMacros Which:=xlAutoOpen 'Enables Macros in Workbook
CurrentWB.Save
ThisName = CurrentWB.Name
For SheetNumber = 1 To CurrentWB.Sheets.Count 'Counts Worksheets in Workbook
If (CurrentWB.Sheets(SheetNumber).Name <> "What If") Then
CurrentWB.Sheets(SheetNumber).Unprotect ("UMC626") 'Unprotects Workbook
With CurrentWB.Sheets(SheetNumber).UsedRange
.Value = .Value
End With
CurrentWB.Sheets(SheetNumber).Protect Password:="UMC626", DrawingObjects:=True, Contents:=True, Scenarios:=True 'Protects Workbook
End If
Next SheetNumber 'Runs Through Iteration
CurrentWB.Cells(1, 1).Select 'Saves each workbook at the top of the page
CurrentWB.SaveAs FileName:=FlattenedFilePath & "\" & ThisName
CurrentWB.Close 'Closes Workbook
FileName = Dir
Loop
End Sub

Excel VBA Check if worksheet exists before copy worksheet to workbook a

I'm trying develop a macro that pulls in all sheets from all workbooks in a folder if that worksheet doesn't already exist in the master workbook.
IE
Folder
|---Summary Sheet.xlsm
|---Sheet 1 date1.xlsx
|---Sheet 2 date2.xlsx
etc.
The macro opens the workbook, renames the sheet to the date off a cell, copies it across then closes it without saving/prompting. I can't seem to incorporate the name check correctly. I've looked over
Test or check if sheet exists
Excel VBA If WorkSheet("wsName") Exists
But lack the experience to properly translate the concepts across.
This is the code so far. Running now throws a runtime error 438 with
sheetToFind = ThisWorkbook.Sheets(1)
Sub ConslidateWorkbooks()
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Dim sheetToFind As String
Dim sheetExists As Boolean
Application.ScreenUpdating = False
Application.DisplayAlerts = False
FolderPath = Environ("userprofile") & "\Folder\"
Filename = Dir(FolderPath & "*.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
sheetExists = False
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Name = Sheet.Range("C4")
sheetToFind = ThisWorkbook.Sheets(1)
If sheetToFind = Sheet.Name Then
sheetExists = True
End If
If sheetExists = False Then
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Workbooks(Filename).Close False
Filename = Dir()
End If
Next Sheet
Loop
Application.ScreenUpdating = True
End Sub
The problem I faced with the answers above were that they didn't check each sheet each time. I found another function from
Excel VBA If WorkSheet("wsName") Exists
Using that I was able to make everything work.
Function sheetExists(sheetToFind As String) As Boolean
sheetExists = False
For Each Sheet In ThisWorkbook.Worksheets
If sheetToFind = Sheet.Name Then
sheetExists = True
Exit Function
End If
Next Sheet
End Function
Sub ConslidateWorkbooks()
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
FolderPath = Environ("userprofile") & "\Folder\"
Filename = Dir(FolderPath & "*.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Name = Sheet.Range("C4")
result = sheetExists(Sheet.Name)
Debug.Print result
If result = True Then
Workbooks(Filename).Close False
Filename = Dir()
End If
If result = False Then
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Workbooks(Filename).Close False
Filename = Dir()
End If
Next Sheet
Loop
Application.ScreenUpdating = True
End Sub

Copy Active sheet of all workbooks in a folder to a new workbook

Hi I have the following code to copy all worksheets of all workbooks in a given folder to a single workbook. I need to modify this code to copy only the active sheet on all workbooks (now it copies all the sheets). Can you help me with this?
Option Explicit
Sub CombineFiles()
Dim Path As String
Dim FileName As String
Dim Wkb As Workbook
Dim WS As Worksheet
Application.EnableEvents = False
Application.ScreenUpdating = False
Path = "C:\" 'Change as needed
FileName = Dir(Path & "\*.xlsx", vbNormal)
Do Until FileName = ""
Set Wkb = Workbooks.Open(FileName:=Path & "\" & FileName)
For Each WS In Wkb.Worksheets
WS.Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Next WS
Wkb.Close False
FileName = Dir()
Loop
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
This way you can do what you want:
Option Explicit
Sub CombineFiles()
Dim Path As String
Dim FileName As String
Dim Wkb As Workbook
Dim WS As Worksheet
Application.EnableEvents = False
Application.ScreenUpdating = False
Path = "C:\" 'Change as needed
FileName = Dir(Path & "\*.xlsx", vbNormal)
Do Until FileName = ""
Set Wkb = Workbooks.Open(FileName:=Path & "\" & FileName)
ActiveSheet.Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
'For Each WS In Wkb.Worksheets
' WS.Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
'Next WS
Wkb.Close False
FileName = Dir()
Loop
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Note:
When you open the workbook, you go over all the sheets with the FOR LOOP, but you only need to copy the ActiveSheet then (as you said) you only need to copy to the new Wrokbook

bringing just one worksheet

Here is a code I have to bring in worksheets from another workbook.
But what I need is to only bring one worksheet (not all of them).
I also need macro to rename the worksheet to something other than what it's called in the original workbook that it's imported from. Can anyone help me with those two tweeks?
Here is what I have:
Option Explicit
Private Sub Bring_Workbooks_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
directory = "access path to where the original workbook is stored"
fileName = Dir(directory & "Name of workboork where sheet will be copied from.xls")
Do While fileName <> ""
Workbooks.Open (directory & fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("Name of my workbook.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("Name of my workbook.xlsm").Worksheets(1)
Next sheet
Workbooks(fileName).Close
fileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Try this code:
Sub Bring_Workbooks_Click()
Dim path, fileName, WkshtOrig, fullName, MyWkbk As String
Dim total As Integer
path = "C:\VBA\" 'access path to where the original workbook is stored
fileName = "OrigWkbk.xlsx" 'Name of workbook where sheet will be copied from.xls
fullName = path & fileName
WkshtOrig = "My Orig Wksht" 'name of worksheet to be copied & placed in this workbook.
MyWkbk = "StkOvrFlwuser3738555.xlsm" 'What I named my sample workbook
Workbooks.Open fileName:= fullName
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks(fileName).Worksheets(WkshtOrig).Copy _
after:=Workbooks(MyWkbk).Worksheets(1)
Workbooks(MyWkbk).Worksheets(WkshtOrig).Select
ActiveSheet.Name = "MyNewName"
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Compile a list/ summary of a specific cell from multiple workbooks with VBA?

I have multiple workbooks in the same layout. In the cell "I8" I have calculated a specific value that I want to compile from all workbooks.
Here is an example of my code:
Sub Code()
Dim file As String
Dim wbResults As Workbook
Dim myPath As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
myPath = "C:\Test\"
file = Dir$(myPath & "*.xls*")
While (Len(file) > 0)
Set wbResults = Workbooks.Open(Filename:=myPath & file, UpdateLinks:=0)
With wbResults.Worksheets(Split(file, ".")(0))
With .Range("I8")
.Formula = "=10^(D28+(I7*I2))"
End With
End With
wbResults.Close SaveChanges:=True
file = Dir
Wend
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
I would like to add to this code and compile a list in another excel workbook where column A puts the name of the file of a workbook and column B puts the value of "I8" in that respective workbook.
Here is my answer:
Sub Code()
Dim file As String
Dim wbResults As Workbook
Dim myPath As String
myPath = "C:\Test\"
'---------------- Create a new workbook then save it ----------------
Dim WBSummary As Workbook
Set WBSummary = Excel.Application.Workbooks.Add
WBSummary.SaveAs myPath & "WBSummary.xls"
'--------------------------------------------------------------------
Application.ScreenUpdating = False
Application.DisplayAlerts = False
file = Dir$(myPath & "*.xls*")
Dim i As Long 'To update row number in WBSummary
While (Len(file) > 0)
i = i + 1
If file <> "WBSummary.xls" Then
Set wbResults = Workbooks.Open(Filename:=myPath & file, UpdateLinks:=0)
With wbResults.Worksheets(Split(file, ".")(0))
With .Range("I8")
.Formula = "=10^(D28+(I7*I2))"
.Calculate 'To update value in "I8"
WBSummary.Worksheets(1).Cells(i, 1).Value = file
WBSummary.Worksheets(1).Cells(i, 2).Value = .Value
End With
End With
wbResults.Close SaveChanges:=True
End If
file = Dir
Wend
WBSummary.Close True 'Close and Save WBSummary
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub