I am quite new to excel VBA macros so my problem should be easily solved.
I am trying to open all files in one folder, edit those files a little bit and copy them to existing workbook. Unfortunately, run-time error '424': Object required, occurs.
Highlighted is row:
ActiveSheets.Copy After:=Workbooks("Macro sheets.xlsm").Sheets(Sheets.Count)
It looks like "Macro sheets.xlsm", does not exists, but that is the name of workbook, from which I run this macro.
I have went through many forums, tried a lot of codes, but still did not find the solution.
Please, can somebody help me?
Thank you a lot,
Jan
Sub nahranidat()
Dim YourFile As Variant
Dim YourFolderPath As Variant
YourFolderPath = "K:\MMR\2015\BO\macro files connection\"
ChDir YourFolderPath
YourFile = Dir(YourFolderPath & "*.*")
Do While YourFile <> ""
Workbooks.Open Filename:=YourFolderPath & YourFile
YourFile = Dir
Set myObject = ActiveWindow
If Activeworkbook.Worksheets.Count = 2 Then
Sheets(1).Select
ActiveSheet.Name = Left(Activeworkbook.Name, InStr(Activeworkbook.Name, ".") - 1) & "_1_month"
Sheets(2).Select
ActiveSheet.Name = Left(Activeworkbook.Name, InStr(Activeworkbook.Name, ".") - 1) & "_by_month"
Activeworkbook.Sheets.Select
ActiveSheets.Copy After:=Workbooks("Macro sheets.xlsm").Sheets(Sheets.Count)
Else
Sheets(1).Select
ActiveSheet.Name = Left(Activeworkbook.Name, InStr(Activeworkbook.Name, ".") - 1)
Activeworkbook.Sheets.Select
ActiveSheets.Copy After:=Workbooks("Macro sheets.xlsm").Sheets(Sheets.Count)
End If
Application.CutCopyMode = False
myObject.Close , SaveChanges:=False
Loop
End Sub
You've referenced ActiveSheets instead of ActiveSheet so VBA will assume you have created a new object. Just change that line to
ActiveSheet.Copy After:=Workbooks("Macro sheets.xlsm").Sheets(Sheets.Count)
It is good practice to declare Option Explicit at the top of each module, that way a 'variable not defined' error makes it easier to spot typographical errors in variable/object names. You can set this automatically by going to VBA>Tools>Options>Editor>Require Variable Declaration.
Related
I am trying to write a code that I copied from somewhere else.
The code is not working and gives me an error.
Can someone please review and advise if there is a syntax error
Dim directory As String, filename As String, sheet As Worksheet, total As Integer
Dim WrdArray() As String
Application.DisplayAlerts = False
directory = "U:\GMR & PAYROLL REPORTS 2018-19\FEBRUARY 2019\COMPLETED\PAYSLIPS\"
filename = Dir(directory & "*.csv")
Do While filename <> " "
Workbooks.Open (directory & filename)
WrdArray() = Split(filename, ".")
For Each sheet In Workbooks(filename).Worksheets
Wookbooks(filename).ActiveSheet.Name = WrdArray(0)
total = Workbooks("PAYSLIPS CONSOL.xlsm").Worksheets.Count
Workbooks(filename).Worksheets(sheet.Name).Copy after:=Workbooks("PAYSLIPS CONSOL.xlxm").Worksheets(total)
GoTo exitFor:
Next sheet
exitFor:
Workbooks(filename).Close
filename = Dir()
Loop
Sheets("ALL HOMES").Select
lastsheets = Worksheets.Count
For i = 2 To lastsheets
mysheet = Sheets(i).Activate
mysheetrow = Cells(Rows.Count, 1).End(x1Up).Row
Range("A1;U" & mysheetrow).Select
Selection.Copy
Sheets("ALL HOMES").Select
lastrow = Cells(Rows.Count, 1).End(x1Up).Row
Range("A1").Select
Range("A" & lastrow).Offset(1, 0).Range("A1").Select
ActiveSheet.Paste
Next i
MsgBox "Your Report is Ready"
Application.DisplayAlerts = True
End Sub
In general, you can use VBA compiler to check whether your project can compile. To do this in the VBA Editor, click Debug -> Compile VBA Project. Everytime you click it, it will either run smoothly and say nothing, or show you the first compilation error in the project it runs into (so you can fix it and click Compile again).
I tried to compile the code you posted:
First, as suggested in the comment, you don't have the Sub line at the top. For example
Sub create_payroll()
, where create_payroll is your preferred name for this macro. Put this line right above all the code you posted in the question.
Second, there is a typo "Wookbooks" instead of Workbooks.
I'm stuck in a problem in VBA while consolidating data from other workbook to master work book and using file name and path name is variable which is changing dynamically in loop i searched but i only find hard coded path so i'm posting here following is my code.
Sub Append()
'Append data from other files
Path = "E:\NPM PahseIII\"
Dim c As Range
'find the first empty cell in ColA
Set c = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(2, 0)
Filename = Dir(Path & "*.xlsx")
Do While Filename <> ""
If InStr(Filename, ".") > 0 Then
Filenamenoext = Left(Filename, InStr(Filename, ".") - 1)
End If
c.Value = Filenamenoext
Set c = c.Offset(1, 0)
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
Windows("Master sheet").Activate
Selection.Consolidate Sources:=Array("'Path & [Filename]Sheet1'!$B$2:$B$5"),
Function:=xlSummary
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
The first problem is that this program gives me the error
Object doesn't support this property or method
at this line
Selection.Consolidate Sources:=Array("'Path & [Filename]Sheet1'!$B$2:$B$5"),
Function:=xlSummary
secondly i want that when first time data is appended by running the code again if there is no change in the other files data then code should not append duplicate again.
Note that in that string "'Path & [Filename]Sheet1'!$B$2:$B$5" the Path and Filename is not considered as a variable but as a hard coded string!
You must use something like
"'" & Path & "[" & Filename & "]Sheet1'!$B$2:$B$5"
if you want to use the variable values.
Also according to the documentation of the Range.Consolidate method the constant of the xlConsolidationFunction is not Function:=xlSummary but Function:=xlSum.
Also note that Selection is very undefined and can be anywhere in that worksheet. I recommend to read How to avoid using Select in Excel VBA and reference your ranges, workbooks etc without using .Activate and .Select or Selection. at all.
How to import a Sheet from an external Workbook AND use the Filename (WITHOUT the .datatype at the end) as the new Worksheet name?
The part with WITHOUT the .datatype at the end I meant because I could split the filename from the file path with UBound, but when I try to do that with the filename and the filetype at the end, it doesn't work and gives me an error. Perhaps i dont understand ubound
well enough.
I found this Sub somewhere here on the forum.
But I don't want to import any sheet except the sheet which has the same name as the file itself. So I am not even sure if you need to specify the sheet name.
So I have this Excel file with VBA macros. And the Sheet is called Blank (Since I can't have an excel file without a sheet inside it) and
I have a Userform button where I browse for the file first, and the sheet there should be imported to my Excel File and delete the Blank sheet and import the new EXTERNAL sheet.
Also, it should import ANY Sheet from the file path. Because the names will always be different.
And also, how do I import the data as csv?
I am googling but I don't see what exactly causes it to be imported as csv at other peoples solutions.
Sub ImportSheet()
Dim sImportFile As String, sFile As String
Dim sThisBk As Workbook, wbBk As Workbook
Dim vfilename As Variant
Dim wsSht As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set sThisBk = ActiveWorkbook
sImportFile = Application.GetOpenFilename( _
FileFilter:="Comma Separated Value, *.csv", Title:="Open Workbook")
If sImportFile = "False" Then
MsgBox "No File Selected!"
Exit Sub
Else
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
Application.Workbooks.Open Filename:=sImportFile
Set wbBk = Workbooks(sFile)
With wbBk
If SheetExists("GaebTesten.g42_2") Then
Set wsSht = .Sheets("GaebTesten.g42_2")
wsSht.Copy Before:=sThisBk.Sheets("Start")
Else
MsgBox "There is no sheet with name :US in:" & vbCr & .Name
End If
wbBk.Close SaveChanges:=False
End With
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Function SheetExists(sWSName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = Worksheets(sWSName)
If Not ws Is Nothing Then SheetExists = True
End Function
this is my second post here on stack overflow, and my first question was very dumb, and when I asked my first question, it was my 2nd hour with vba.
I think I am at about 30 hours now and I've learned a lot.
Question: I am doing this Excel Macro in VBA with userform too now. But mostly I google how to do what and I try to implement it WHILE understanding it, I don't just copy and paste code. Often I just do line by line and test it out.
BUT... how do you guys remember all that?
If I had to program the same thing again right now, I won't know how to, because I know how a syntax works, but I wouldn't know which syntax and stuff to actually use to achieve the desired effect...
Does it come from repeating the same things = experience?
Or how do you acquire the abilities to code without googling almost every single thing? When watching youtubers live streaming how they code something, they never look it up on the internet....
Let me present you a different way than pure string manipulation:
Set a new reference to Microsoft Scripting Runtime. This will enable the Scripting namespace. With it you can do things like the following:
sImportFile = "C:\StackFolder\PrintMyName.xlsx"
With New Scripting.FileSystemObject
Debug.Print .GetBaseName(sImportFile)
' Outputs "PrintMyName"
Debug.Print .GetExtensionName(sImportFile)
' Outputs "xlsx"
Debug.Print .GetFileName(sImportFile)
' Outputs "PrintMyName.xlsx"
Debug.Print .GetDriveName(sImportFile)
' Outputs "C:"
Debug.Print .GetParentFolderName(sImportFile)
' Outputs "C:\StackFolder"
End With
You can build a little helper function to give you the part of the file name you need:
Public Function GetFilenameWithoutExtension(ByVal filename as String) as String
With New Scripting.FileSystemObject
GetFilenameWithoutExtension = .GetBaseName(filename)
End With
End Function
and call it: sFile = GetFilenameWithoutExtension(sImportFile)
Regarding the interesting use of UBound in your subroutine, you could even get the filename (without extension) that way - assuming it doesn't contain additional dots:
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
SplitName = Split(sFile, ".")
FilenameWithoutExtension = SplitName(UBound(SplitName)-1)
Extension = SplitName(UBound(SplitName))
These are, however, purely academical thoughts and I wouldn't recommend doing it this way.
Here are two ways to extract the workbook name without the file extension. Here I am removing the extension .xlsx. If the extension is constant, you can just hard code it. If not, you can use wildcards also
MsgBox Left(wbBk.Name, Len(ThisWorkbook.Name) - 5)
MsgBox Replace(wbBk.Name, ".xlsx", "")
You can refer to the sheet with the same name as the workbook by using something like
Sheets(Left(wbBk.Name, Len(ThisWorkbook.Name) - 5).Copy
Sheets(Replace(wbBk.Name, ".xlsx", "").Copy
You can use InstrRev. It is efficient as starts from the end of the string which is where the extension is located.
Left$(wbBk.Name, InStrRev((wbBk.Name, ".") - 1)
I built a program to copy sheet one from all books in a directory, and paste them into the active workbook. I have roughly 1200 books in the directory, and without fail each time I run it excel reboots after around #125. No error messages. Anyway of getting around this?
Sub GetSheets()
Path = "C:\Users\bdaly\Desktop\Formulas\smaller sample\"
Dim DestWB As Workbook
Set DestWB = ThisWorkbook
Filename = Dir(Path & "*.xls")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
Sheets("Sheet1").Copy After:=DestWB.Sheets(DestWB.Sheets.Count)
Application.DisplayAlerts = False
Workbooks(Filename).Close
Application.DisplayAlerts = True
Filename = Left(Left(Filename, Len(Filename) - 4), 31)
DestWB.Sheets(DestWB.Sheets.Count).Name = Filename
Filename = Dir()
Loop
End Sub
Edit: As advised I removed the offending file, Excel still reboots after 124 loops.
Not sure if this is going to address the problem at hand, but it will help in debugging or exposing the problem.
Put simply, qualify your source data.
Include Dim SourceWB as Workbook. This could be done where you declare DestWB.
Change Workbooks.Open Filename:=Path & Filename, ReadOnly:=True to Set SourceWB = Workbooks.Open(Filename:=Path & Filename, ReadOnly:=True, Editable:=True)
Change Sheets("Sheet1").Copy After:=DestWB.Sheets(DestWB.Sheets.Count) to SourceWB.Sheets("Sheet1").Copy After:=DestWB.Sheets(DestWB.Sheets.Count)
Change Workbooks(Filename).Close to SourceWB.Close
Unfortunately, the .Copy command is a Sub, not a Function - would be so much more neater if it provided a reference to the sheet that has just been created as you could then use it in DestWB.Sheets(DestWB.Sheets.Count).Name = Filename
I suggest, for debugging purposes, keeping the DisplayAlerts on for now. This may provide a clue as to where the fault is happening.
Also include some debug.print lines in your loop. Finding where in the loop it crashes could help diagnose the issue. Make them a little descriptive, the ones I would think of are:
debug.print "Entered loop"
debug.print "Copied file"
debug.print "renamed file"
'debug.print "new FileName is " & FileName`.
You get the idea.
Try the AddIn from the link below.
https://www.rondebruin.nl/win/addins/rdbmerge.htm
I got problems in making the files search using workbooks.open. When the macro is executed, it shows runtime error "1004". Actually, I learn this from YouTube.
Can anyone know what's the problems?
This code actually find multiple excel files in one folder that we path.
Sub checkcopy()
Dim cf As String
Dim erow
cf = Dir("C:\Supplier\")
Do While Len(cf) > 0
MsgBox ("Check")
If cf = "SummaryCheckFile.xlsm" Then
Exit Sub
End If
MsgBox ("Check 1")
Workbooks.Open (cf)
Range("A1:E1").Copy
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 4))
checkFile = Dir
Loop
End Sub
Sorry,
its show
'go.xls' not found be found. Check The spelling of the file name and verify the file location is correct.
If you are trying to open the file from your list of mostly recently used files, make sure.....
Dir() only returns the filename - it does not include the path, so you need to specify both of those when you call Workbooks.Open()
Also your loop will never exit (unless the first file is "SummaryCheckFile.xlsm") because all other calls to Dir() assign the return value to checkFile, so cf will never be cleared.
Sub checkcopy()
Const FLDR As String = "C:\Supplier\"
Const EXCLUDE_FILE As String = "SummaryCheckFile.xlsm"
Dim cf As String, c As Range, wb As Workbook
'set the first copy destination
Set c = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
cf = Dir(FLDR & "*.xls*", vbNormal) 'only Excel files
Do While Len(cf) > 0
Debug.Print cf
'opening this file ?
If UCase(cf) <> UCase(EXCLUDE_FILE) Then
Set wb = Workbooks.Open(FLDR & cf, ReadOnly:=True)
wb.Sheets(1).Range("A1:E1").Copy c 'assumes copying from the first sheet
Set c = c.Offset(1, 0) 'next destination row
wb.Close False
End If
cf = Dir 'next file
Loop
End Sub
Try to give the path of cf, for example cf = "c:\XXX\filename.xlsm", rather than cf = "filename.xlsm".
Try to work with the parameter CorruptLoad when opening the xlsm which contains macros and causing runtime errors and no response.
Application.DisplayAlerts = False
Workbooks.Open ("enter your file path here"), CorruptLoad:=xlExtractData
Application.DisplayAlerts = True