Object required error when trying to get End(xlDown) + 1 row - vba

I have this code that opens first workbook, second workbook, copies a range from the first one and pastes it into the second one. I want to make it select the cell right after the pasted range in the second workbook, but it failes with Object required error.
Sub tes()
'**VARIABLES**
Dim folderPath As String
folderPath = "Y:\plan_graphs\final\mich_alco_test\files\"
Dim fileTitle As String
fileTitle = "5.xlsx"
Dim dataWorkbook As Workbook
Set dataWorkbook = Application.Workbooks.Open(folderPath & fileTitle)
Dim copyRange As Range
Set copyRange = dataWorkbook.Worksheets("List1").Range("A3:F3", Range("A3").End(xlDown))
Dim resultWorkbook As Workbook
Set resultWorkbook = Application.Workbooks.Open("Y:\plan_graphs\final\mich_alco_test\result.xlsx")
copyRange.Copy
resultWorkbook.Worksheets("1").Range("A3").PasteSpecial Paste:=xlPasteFormulas
Dim nextRange As Range
Set nextRange = resultWorkbook.Worksheets("1").Range("A3:F3", _
resultWorkbook.Worksheets("1").Range("A3").End(xlDown)).Offset(1, 0).Select
End Sub
What am I doing wrong?

You can't Set the range and Select it in the same line, try the code section below:
copyRange.Copy
With resultWorkbook.Worksheets("1")
.Range("A3").PasteSpecial Paste:=xlPasteFormulas
Dim nextRange As Range
Set nextRange = .Range("A3").End(xlDown).Offset(1, 0) ' set the Range first
nextRange.Select ' <-- select the Range
End With
End Sub

Related

Run-Time Error '6' overflow (copy range from closed workbook)

I have the below code placed on my active workbook which copy's data from a closed workbook. It works fine and very fast but i can only copy up to 8 columns if I select more than that I get a
run-time error 6 - Overflow
Code:
Sub Get_Data()
Dim RngToCopy As Range
Dim wkbk As Workbook
Dim DestCell As Range
Dim myFileNames As Variant
Dim iCtr As Long
Dim testStr As String
Set DestCell = ThisWorkbook.Worksheets(1).Range("a1")
myFileNames = Array("C:\my documents\excel\book1.xlsm") ' i could add more workbooks to copy from and append on current worksheet
For iCtr = LBound(myFileNames) To UBound(myFileNames)
testStr = ""
On Error Resume Next
testStr = Dir(myFileNames(iCtr))
On Error GoTo 0
If testStr = "" Then
MsgBox myFileNames(iCtr) & " doesn't exist!"
Else
Set wkbk = Workbooks.Open(Filename:=myFileNames(iCtr))
With wkbk.Worksheets(1)
Set RngToCopy = .Range("a2:r2", _
.Cells(.Rows.Count, "A").End(xlUp))
End With
DestCell.Resize(RngToCopy.Rows.Count, _
RngToCopy.Columns.Count).Value _
= RngToCopy.Value
Set DestCell = DestCell.Offset(RngToCopy.Rows.Count, 0)
wkbk.Close savechanges:=False
End If
Next iCtr
End Sub
when I debug the line that it goes to is: where am I going wrong :(
DestCell.Resize(RngToCopy.Rows.Count, _
RngToCopy.Columns.Count).Value _
= RngToCopy.Value
the source workbook is a big file with a lot of data, I tried most of the suggestions when I researched on the error but no luck.
if it helps workbook contains 18 columns and 300k+ rows
Try a different approach, use Copy >> PasteSpecial (values only) :
' 1st: set copy range
With wkbk.Worksheets(1)
Set RngToCopy = .Range("A2:R2", .Cells(.Rows.Count, "A").End(xlUp))
End With
' 2nd: set destination range start position
Set DestCell = DestCell.Offset(RngToCopy.Rows.Count, 0)
' 3rd: use copy>>paste special (values only)
RngToCopy.Copy
DestCell.PasteSpecial xlPasteValues

Automatically update macro when changing filename

I have the following macro to filter specific data out of my directory with employee hours files and place it into my zmaster file. However, I need various master documents for various projects (EG. change name to: "project 300000"). When I change my master file name from zmaster to anything else, my macro cannot find the appropriate file, obviously.
Is there a way to change my macro in such a way that zmaster.xlsm is automatically replaced in my macro by the current file name?
Option Explicit
Sub CopyToMasterFile()
Dim MasterWB As Workbook
Dim MasterSht As Worksheet
Dim MasterWBShtLstRw As Long
Dim FolderPath As String
Dim TempFile
Dim CurrentWB As Workbook
Dim CurrentWBSht As Worksheet
Dim CurrentShtLstRw As Long
Dim CurrentShtRowRef As Long
Dim CopyRange As Range
Dim ProjectNumber As String
FolderPath = "C:\test\"
TempFile = Dir(FolderPath)
Dim WkBk As Workbook
Dim WkBkIsOpen As Boolean
'Check if zmaster is open already
For Each WkBk In Workbooks
If WkBk.Name = "zmaster.xlsm" Then WkBkIsOpen = True
Next WkBk
If WkBkIsOpen Then
Set MasterWB = Workbooks("zmaster.xlsm")
Set MasterSht = MasterWB.Sheets("Sheet1")
Else
Set MasterWB = Workbooks.Open(FolderPath & "zmaster.xlsm")
Set MasterSht = MasterWB.Sheets("Sheet1")
End If
ProjectNumber = MasterSht.Cells(1, 1).Value
Do While Len(TempFile) > 0
'Checking that the file is not the master and that it is a xlsx
If Not TempFile = "zmaster.xlsm" And InStr(1, TempFile, "xlsx", vbTextCompare) Then
Set CopyRange = Nothing
'Note this is the last used Row, next empty row will be this plus 1
With MasterSht
MasterWBShtLstRw = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Set CurrentWB = Workbooks.Open(FolderPath & TempFile)
Set CurrentWBSht = CurrentWB.Sheets("Sheet1")
With CurrentWBSht
CurrentShtLstRw = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
For CurrentShtRowRef = 1 To CurrentShtLstRw
If CurrentWBSht.Cells(CurrentShtRowRef, "A").Value = ProjectNumber Then
'This is set to copy from Column A to Column L as per the question
If CopyRange Is Nothing Then
'If there is nothing in Copy range then union wont work
'so first row of the work sheet needs to set the initial copyrange
Set CopyRange = CurrentWBSht.Range("A" & CurrentShtRowRef & _
":L" & CurrentShtRowRef)
Else
'Union is quicker to be able to copy from the sheet once
Set CopyRange = Union(CopyRange, _
CurrentWBSht.Range("A" & CurrentShtRowRef & _
":L" & CurrentShtRowRef))
End If ' ending If CopyRange Is Nothing ....
End If ' ending If CurrentWBSht.Cells....
Next CurrentShtRowRef
CopyRange.Select
'add 1 to the master file last row to be the next open row
CopyRange.Copy MasterSht.Cells(MasterWBShtLstRw + 1, 1)
CurrentWB.Close savechanges:=False
End If 'ending If Not TempFile = "zmaster.xlsx" And ....
TempFile = Dir
Loop
ActiveSheet.Range("A1:L200").RemoveDuplicates Columns:=Array(1, 2, 4, 8, 9, 10, 11, 12), Header:=xlYes
End Sub
One way to escape from hard coded workbook names is to use ActiveWorkbook or ThisWorkbook objects - they both return instance of Workbook object.
ThisWorkbook
Returns a Workbook object that represents the workbook
where the current macro code is running. Read-only.
ActiveWorkbook
Returns a Workbook object that represents the workbook in the active
window (the window on top). Read-only. Returns Nothing if there are no
windows open or if either the Info window or the Clipboard window is
the active window.
Then you can get the name of the workbook with Name property of the returned Workbook object.
Another way could be if you pass such a data as parameter to your functions.
For example:
Sub CopyToMasterFile(wbName as String, sheetName as String)
In this variant if you call your Sub from another macro code, you can pass whatever you want to use - this ways you can escape the hard coded stuff in your functions.
This is also valid for the Worksheet objects - have a look on the ActiveSheet

I get a Run-time Error #1004 for my VBA code with a Named range?

why does this code run fine:
Sub SelectRange()
Dim sourceBook As Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet
Set sourceBook = ActiveWorkbook
Set sourceSheet = sourceBook.Sheets("Tabelle1")
ActiveWorkbook.Names.Add _
Name:="ggg", _
RefersTo:="=Sheet1!A4:L37"
sourceSheet.Select
sourceSheet.Range("A4:L37").Select
End Sub
However if I change
sourceSheet.Range("A4:L37").Select
to:
sourceSheet.Range("ggg").Select
I receive a run-time error 1004
Try the code below, it will create "ggg" named range from cells "A4:L37" in "Tabelle1" sheet.
Afterwards, it sets another Range MyNamedRange to the named Range("ggg") - this step is not necessary, I just like to work with variables for Range.
At the end, it selects MyNamedRange.
Code
Sub SelectRange()
Dim sourceBook As Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet
Dim MyNamedRange As Range
Set sourceBook = ActiveWorkbook
Set sourceSheet = sourceBook.Sheets("Tabelle1")
' create the named range "ggg"
sourceBook.Names.Add _
Name:="ggg", _
RefersTo:="=" & sourceSheet.Name & "!A4:L37"
Set MyNamedRange = Range("ggg") ' <-- set the Range to your NamedRange "ggg"
sourceSheet.Activate '<-- activate the sheet first
MyNamedRange.Select '<-- select the Named Range
End Sub
Try this:
SourceSheet.Range(Names.Item("ggg")).Select

1004 error for using usedrange

I am trying to copy over values from one workbook to another using the usedrange function (there are some blanks in certain rows and it is fine to copy over the blank as well), but I am getting the 1004 error:
Sub ActiveInactiveVendors()
Dim ActiveWkb As Workbook, Wkb As Workbook, InactiveWkb As Workbook
Dim ActiveWkst As Worksheet, Wkst As Worksheet, InactiveWkst As Worksheet
Dim aCell As Range
Dim targetRng As Range
Set ActiveWkb = Workbooks.Open("C:\Users\clara\Desktop\active vendors.xlsx")
Set Wkb = ThisWorkbook
Set Wkst = Wkb.Sheets("Vendors")
Set ActiveWkst = ActiveWkb.Worksheets("aqlc7da48e7")
'set column A starting from A7
Set targetRng = Wkst.Range("A7" & Wkst.Rows.Count)
'get the values starting from a32 to the last row used and set it in wkst
targetRng.Value = ActiveWkst.Range("A32" & ActiveWkst.UsedRange.Rows.Count).Value
End Sub
I appreciate any feedback! Thank you
This line:
Set targetRng = Wkst.Range("A7" & Wkst.Rows.Count)
is not correct. You are not getting A7:A1048576 but a concatenating of the two. So it is looking for A71048576 which does not exist
Then you should use similar sized ranges when setting values.
Sub ActiveInactiveVendors()
Dim ActiveWkb As Workbook, Wkb As Workbook, InactiveWkb As Workbook
Dim ActiveWkst As Worksheet, Wkst As Worksheet, InactiveWkst As Worksheet
Dim aCell As Range
Dim targetRng As Range, origRng As Range
Set ActiveWkb = Workbooks.Open("C:\Users\clara\Desktop\active vendors.xlsx")
Set Wkb = ThisWorkbook
Set Wkst = Wkb.Sheets("Vendors")
Set ActiveWkst = ActiveWkb.Worksheets("aqlc7da48e7")
'set column A starting from A7
Set origRng = ActiveWkst.Range("A32", ActiveWkst.Cells(ActiveWkst.Rows.Count, 1).End(xlUp))
Set targetRng = Wkst.Range("A7", Wkst.Cells(origRng.Rows.Count + 6, 1))
'get the values starting from a32 to the last row used and set it in wkst
targetRng.Value = origRng.Value
End Sub

Got stuck in using transpose

I was attempting to extract data from other workbooks into a master workbook. All of these workbooks were saved in one folder. And I wanted to open other workbooks automatically not manually. The data that I need to extract are non adjacent cells, and I want the data extracted from each source workbook to be shown in rows in the master workbook (because I have a head line in row 1, so after extracting data from the first workbook and paste in row 2, the data extracted from the second workbook will be listed in row 3 and so on)
However, when I ran the macro I got stuck in Transpose.
Below is my code
Sub LoopThroughDirectory()
Dim MyFile As String
Dim wkbSource As Workbook
Dim wkbTarget As Workbook
Dim erow As Single
Dim Filepath As String
Dim copyRange As Range
Dim cel As Range
Dim pasteRange As Range
Filepath = "C:\xxxxx\"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "Import Info.xlsm" Then GoTo NextFile
Set wkbTarget = Workbooks("Import Info.xlsm")
Set wkbSource = Workbooks.Open(Filepath & MyFile)
Set copyRange = wkbSource.Sheets("sheet1").Range("c3,f6,f9,f12,f15,f19,f21,f27,f30,f33,f37,f41")
Set pasteRange = wkbTarget.Sheets("sheet1").Range("a1")
For Each cel In copyRange
cel.Copy
ecolumn = wkbTarget.Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Offset(0, 1).Column
wkbTarget.Worksheets("Sheet1").Paste Destination:=wkbTarget.Worksheets("Sheet1").Range(Cells(1, ecolumn).Address)
pasteRange.Cells(1, ecolumn).PasteSpecial xlPasteValues
Next
Application.CutCopyMode = False
wkbSource.Close
NextFile:
MyFile = Dir
Loop
End Sub
What I have done so far:
I transposed the data I extracted from source workbooks but they were not shown in the master workbook as what I expected. All of them are in row 1
I don't have much experience in VBA and I feel like the code I wrote to copy non adjacent cells and transpose in the master workbook makes the loop much more complicated. But I don't know where I went wrong or how to fix that.
Please help me. Thank you so much!
You have to set the destination range outside of the loop and offset it inside of the loops:
Sub LoopThroughDirectory()
Dim Filepath As String, MyFile As String
Dim wkbSource As Workbook, wkbTarget As Workbook
Dim copyRange As Range, cel As Range, pasteRange As Range
Set wkbTarget = Workbooks("Import Info.xlsm")
Set pasteRange = wkbTarget.Sheets("sheet1").Range("a2") ' start at row 2
Filepath = "C:\xxxxx\"
MyFile = Dir(Filepath)
While MyFile > ""
If MyFile = "Import Info.xlsm" Then GoTo NextFile
Set wkbSource = Workbooks.Open(Filepath & MyFile)
Set copyRange = wkbSource.Sheets("sheet1").Range("c3,f6,f9,f12,f15,f19,f21,f27,f30,f33,f37,f41")
For Each cel In copyRange
pasteRange.Value = cel.Value ' "copy" the value
Set pasteRange = pasteRange.Offset(, 1) ' move to the next column
Next
wkbSource.Close
Set pasteRange = pasteRange.EntireRow.Resize(1,1) ' move back to the first cell in the row
Set pasteRange = pasteRange.Offset(1) ' move to the cell bellow (next row)
NextFile:
MyFile = Dir
Wend
End Sub