Paste gives "Object required" error - database

I get this error:
Error 424: Object required
on this line:
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 1))
in the code below. Why?
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\Users\Julio Jesus Sanchez\Desktop\MRSK TXT\"
MyFile = Dir("C:\Users\Julio Jesus Sanchez\Desktop\MRSK TXT\")
Do While Len(MyFile) > 0
If MyFile = "MRSK DATABASE.xlsm" Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Range("A1:K1").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, 1))
MyFile = Dir
Loop
End Sub

You close the ActiveWorkbook and then refer to ActiveSheet, which ActiveSheet do you mean? If it is the master book you refer to then you should explicitly tell it that by setting it as an object, also is your VBA in a MS Access module or in Excel? You just tagged this as Database and VBA, I guess Excel as you don't have any reference to the Excel object.
Dim sh as Worksheet
Set sh = Workbooks("NameOfWorkBook.xlsx").WorkSheets("WorksheetName")
Then whenever you refer to the sheet:
sh.Paste Destination:=sh.Range(Cells(erow, 1), Cells(erow, 1))

Related

Subscript out of range when trying to loop through array to read values

I have a string of predefined worksheets, that I need to run specific code for. I get a compile error.
The code is set up to copy data from one sheet to another.
How do I do the same for multiple sheets?
When I step through the code sht is showing the MHP60,MHP61,MHP62 and not just MHP60.
I get a subscript out of range error.
Sub Prepare_CYTD_Report()
Dim addresses() As String
Dim addresses2() As String
Dim SheetNames() As String
Dim SheetNames2() As String
Dim wb1 As Workbook, wb2 As Workbook
Dim my_Filename
'Declare variables for MHP60, MHP61, MHP62 Trial Balance Values
Dim i, lastcol As Long
Dim tabNames, cell As Range
Dim tabName As String
Dim sht As Variant
addresses = Strings.Split("A9,A12:A26,A32:A38,A42:A58,A62:A70,A73:A76,A83:A90", ",") 'Trial Balance string values
addresses2 = Strings.Split("G9,G12:G26,G32:G38,G42:G58,G62:G70,G73:G76,G83:G90", ",") 'Prior Month string values
SheetNames = Strings.Split("MHP60,MHP61,MHP62")
'SheetNames2 = Strings.Split("MHP60-CYTDprior,MHP61-CYTDprior,MHP62-CYTDprior")
Set wb1 = ActiveWorkbook 'Revenue & Expenditure Summary Workbook
'*****************************Open CYTD files
my_Filename = Application.GetOpenFilename(fileFilter:="Excel Files,*.xl*;*.xm*", Title:="Select File to create CYTD Reports")
If my_Filename = False Then
Exit Sub
End If
Application.ScreenUpdating = False
Set wb2 = Workbooks.Open(my_Filename)
'*****************************Load Column Header Strings & Copy Data
For Each sht In SheetNames
lastcol = wb1.Sheets(sht).Cells(5, Columns.Count).End(xlToLeft).Column
On Error Resume Next
Set tabNames = wb1.Sheets(sht).Cells(4, 3).Resize(1, lastcol - 2).SpecialCells(xlCellTypeConstants)
'actual non-formula text values on row 4 from column C up to column lastCol'
On Error GoTo 0
If Err.Number <> 0 Then
MsgBox "No headers were found on row 4 of MHP60", vbCritical
Exit Sub
End If
For Each cell In tabNames
tabName = Strings.Trim(cell.Value2)
'dedicated variable in case of requirement for further parsing (space/comma elimination?)'
If CStr(wb1.Sheets(sht).Evaluate("ISREF('[" & wb2.Name & "]" & tabName & "'!$A$1)")) = "True" Then
'If wb2 has a tab named for the value in tabName
For i = 0 To UBound(addresses)
wb2.Sheets(tabName).Range(addresses(i)).Value2 = wb1.Sheets(sht).Range(addresses(i)).Offset(0, cell.Column - 1).Value2
'Debug.Print "data for " & wb2.Sheets(tabName).Range(addresses(i)).Address(, , , True) & " copied from " & wb1.Sheets("MHP60").Range(addresses(i)).Offset(0, cell.Column - 1).Address(, , , True)
Next i
Else
Debug.Print "A tab " & tabName & " was not found in " & wb2.Name
End If
Next cell
Next sht
MsgBox "CYTD Report Creation Complete", vbOKOnly
Application.ScreenUpdating = True
End Sub
Split by what?
SheetNames = Strings.Split("MHP60,MHP61,MHP62")
Split by comma? Then use the following instead:
SheetNames = Strings.Split("MHP60,MHP61,MHP62", ",")
Alternative
Dim SheetNames() As Variant ' needs to be Variant to work with Array()
SheetNames = Array("MHP60", "MHP61", "MHP62")
This should be quicker as your macro does not need to split the string and has it as array directly.

Runtime error : Automation Error , The interface is unknown

I am getting runtime error "interface is unknown".
I have used the code.
Don't know why I am getting this error.
Run-time error ‘-2147023179 (800706b5)”: Automation error The
interface is unkown.
Sub copy_sheet_from_folder(ws_the_tool As Workbook)
Dim source As String
Dim strFile As String
Dim wb_from As Workbook
source = ws_the_tool.Path
If InStr(1, source, "http") Then
Dim IE As InternetExplorerMedium
Set IE = New InternetExplorerMedium
IE.Visible = False
IE.Navigate source
Do While IE.ReadyState <> 4
DoEvents
Loop
IE.Quit
Set IE = Nothing
Dim bIsSSL As Boolean
bIsSSL = InStr(1, source, "https:") > 0
source = Replace(Replace(source, "/", "\"), "%20", " ")
source = Replace(Replace(source, "https:", vbNullString), "http:", vbNullString)
source = Replace(source, Split(source, "\")(2), Split(source, "\")(2) & "#SSL\DavWWWRoot")
If Not bIsSSL Then source = Replace(source, "#SSL\", vbNullString)
End If
source = source & "\measure_files\"
strFile = Dir(source)
Do While Len(strFile) > 0
Workbooks.Open Filename:=source & strFile
strFile = Dir()
Set wb_from = ActiveWorkbook
Call copy_sheets(ws_the_tool, wb_from)
wb_from.Close savechanges:=False
Loop
'Call copy_sheets(ws_the_tool)
End Sub
Please suggest why I am getting this error. I have searched this error message and can't find a solution that seems to work for me.

Keep Array value when Sub is looping

I currently have this code that finds all files and folders and writes it to a table. The problem is is that is it sometimes slow.
The code below is modified so that it writes to an array but I am having issues passing the array on when the code loops.
Ultimately, I would like the array to pass on to the first sub so that I can transpose it into the table at once.
Sub FileAndFolder()
Dim FSOLibrary As Object
Dim FSOFolder As Object
Dim FolderName As String
Dim FilesTbl As ListObject
Set FilesTbl = Range("FilesTbl").ListObject
'Set the folder name to a variable
FolderName = Left$(ActiveWorkbook.Path, InStrRev(ActiveWorkbook.Path, "\"))
'Set the reference to the FSO Library
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
'Another Macro must call LoopAllSubFolders Macro to start
LoopAllFolders FSOLibrary.GetFolder(FolderName)
'return TempArray here and paste into table
'Range(FilesTbl.ListColumns("File Name").DataBodyRange(1)) = TempArray
End Sub
Sub LoopAllFolders(FSOFolder As Object)
'Don’t run the following macro, it will be called from the macro above
Dim FSOSubFolder As Object
Dim FSOFile As Object
Dim FolderPath As String
Dim FileName As String
Dim TempArray() As String
'For each subfolder call the macro
For Each FSOSubFolder In FSOFolder.SubFolders
LoopAllFolders FSOSubFolder
Next
'For each file, print the name
For Each FSOFile In FSOFolder.Files
'Insert the actions to be performed on each file
FileName = FSOFile.Name
FolderPath = FSOFile.ParentFolder
If Left(FileName, 2) = "~$" Then GoTo NEXTINLOOP
ReDim Preserve TempArray(0 To 3, 0 To i)
TempArray(0, i) = FileName
TempArray(1, i) = FolderPath & "\" & FileName 'file
TempArray(2, i) = FolderPath 'folder
TempArray(3, i) = FolderPath & "\" & FileName 'showpath
i = i + 1
NEXTINLOOP:
Next
End Sub 'TempArray and i clears here
Thanks.
You either need to declare a variable at the module level so that the list of folder information is available to all methods in the module, or change 'LoopAllFolders' to a Function so that you can return the information you have collated.
The function below will return a Variant which contains an array of arrays (normally called a jagged array). You access the jagged array using this nomenclature
Varname(x)(y)
You will need a variable in the calling method to receive the jagged array
e.g.
Dim myFileInfo as Variant
MyFileInfo = LoopAllFolders(FSOLibrary.GetFolder(FolderName))
Here is the updated function
Public Function LoopAllFolders(FSOFolder As Scripting.FileSystemObject) As Variant
'Don’t run the following macro, it will be called from the macro above
Dim FileInfo As Scripting.Dictionary: Set myFileInfo = New Scripting.Dictionary
'For each subfolder call the macro
Dim FSOSubFolder As Scripting.Folder
For Each FSOSubFolder In FSOFolder.SubFolders
LoopAllFolders FSOSubFolder
Next
'For each file, print the name
Dim FSOFile As Scripting.File
For Each FSOFile In FSOFolder.Files
'Insert the actions to be performed on each file
Dim FileName As String
FileName = FSOFile.Name
Dim FolderPath As String
FolderPath = FSOFile.ParentFolder
If Not Left(FileName, 2) = "~$" Then
myFileInfo.Add Array(FileName, FolderPath & "\" & FileName, FolderPath, FolderPath & "\" & FileName)
End If
Next
LoopAllFolders = myFileInfo.Items
End Function
The above code may not be perfect but at least it points you in the right direction.
Based on your question, you might do well by working through a VBA tutorial as functions are fairly fundamental, and if you are unaware of them......
To help you on your journey I'd also recommend installing the fantastic and free RubberDuck addin.
Create a List of Files all subfolders of a Folder
I do not understand what you're doing with FilesTbl, so I modified your solution to create a new workbook with the result. Surely you will figure out how to apply it to the table.
A Quick Fix
Option Explicit
Sub FileAndFolder()
Dim FSOLibrary As Object
Dim FSOFolder As Object
Dim FolderName As String
Dim FilesTbl As ListObject
'Set FilesTbl = Range("FilesTbl").ListObject
'Set the folder name to a variable
FolderName = Left$(ActiveWorkbook.Path, InStrRev(ActiveWorkbook.Path, "\"))
'Set the reference to the FSO Library
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Dim TempArray() As Variant ' ByRef
'Another Macro must call LoopAllSubFolders Macro to start
LoopAllFolders FSOLibrary.GetFolder(FolderName), TempArray
'return TempArray here and paste into table
With Workbooks.Add
With ActiveSheet.Range("A1").Resize(UBound(TempArray, 2), UBound(TempArray))
.Value = Application.Transpose(TempArray)
End With
.Saved = True
End With
'Range(FilesTbl.ListColumns("File Name").DataBodyRange(1)) = TempArray
End Sub
Sub LoopAllFolders(FSOFolder As Object, ByRef TempArray As Variant)
'Don’t run the following macro, it will be called from the macro above
Dim FSOSubFolder As Object
Dim FSOFile As Object
Dim FolderPath As String
Dim FileName As String
Dim i As Long
'Dim TempArray() As String
'For each subfolder call the macro
For Each FSOSubFolder In FSOFolder.SubFolders
LoopAllFolders FSOSubFolder, TempArray
Next
'For each file, print the name
For Each FSOFile In FSOFolder.Files
'Insert the actions to be performed on each file
FileName = FSOFile.Name
FolderPath = FSOFile.ParentFolder
If Left(FileName, 2) = "~$" Then GoTo NEXTINLOOP
i = i + 1
ReDim Preserve TempArray(1 To 4, 1 To i)
TempArray(1, i) = FileName
TempArray(2, i) = FolderPath & "\" & FileName 'file
TempArray(3, i) = FolderPath 'folder
TempArray(4, i) = FolderPath & "\" & FileName 'showpath
NEXTINLOOP:
Next
End Sub 'TempArray and i clears here

Excel VBA: array of Sheets, Copy from one Workbook to another

I'm trying to write a simple VBA Subroutine that:
creates a new workbook in the same directory of the excel file that contains the code ("original file" from here onward)
saves the new workbook as _export.xlsx
copies some predefined sheets from the original file to the "*_export" one.
This is what I've got at the time being:
Sub export()
Dim myPath, folderPath, fileName, exportFileFullPath As String
Dim arrayOfSheetsToCopy As Variant
folderPath = Application.ActiveWorkbook.Path
fullPath = Application.ActiveWorkbook.FullName
fileName = Replace(Application.ActiveWorkbook.Name, ".xlsm", "")
exportFileFullPath = folderPath & "\" & fileName & "_export.xlsx"
Workbooks.Add
ActiveWorkbook.SaveAs fileName:=exportFileFullPath, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
arrayOfSheetsToCopy = Array("originalSheet1", "originalSheet2", "originalSheet3")
Workbooks(fullPath).Sheets(arrayOfSheetsToCopy).Copy After:=Workbooks(exportFileFullPath).Sheets(Sheets.Count)
End Sub
The code seems to run until a "Subscript out of range" error at Sheets(arrayOfSheetsToCopy).Copy...
Initially I though to some kind of syntax error in the definition of the Array of Sheets, so I tried to write a separate .Copy instruction for each Sheet. The same code interrupts at the same point with the same error.
Any idea? Thank you!
Workbook.FullName does not return a valid argument for the Workbooks collection.
You can test this by running ?Workbooks(ActiveWorkbook.FullName).FullName in the Immediate Window - it will error. On the other hand, Workbook.Name does work, so ?Workbooks(ActiveWorkbook.Name).FullName will not error. In other words Workbooks("C:\Users\fabbius\Documents\SomeFile.xlsx") is not valid, while Workbooks("SomeFile.xlsx") is valid, so long as a file by that name is open.
However, I fail to see the benefit of using FullName over using properly defined Workbook Objects:
Sub export()
Dim exportFileFullPath As String, arrayOfSheetsToCopy As Variant
Dim wsExportFrom As Workbook, wsExportTo As Workbook
Set wsExportFrom = ActiveWorkbook
Set wsExportTo = Workbooks.Add
exportFileFullPath = Replace(wsExportFrom.FullName, ".xlsm", "_export.xlsx", Len(wsExportFrom.Path))
'The Len() is in case the File Path contains ".xlsm" for some reason
wsExportTo.SaveAs fileName:=exportFileFullPath, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
arrayOfSheetsToCopy = Array("originalSheet1", "originalSheet2", "originalSheet3")
wsExportFrom.Sheets(arrayOfSheetsToCopy).Copy after:=wsExportTo.Sheets(wsExportTo.Sheets.Count)
End Sub
Of course, if this Macro is being run from the workbook you intend to export from, then With and ThisWorkbook make things even simpler:
Sub export()
Dim exportFileFullPath As String, arrayOfSheetsToCopy As Variant
exportFileFullPath = Replace(ThisWorkbook.FullName, ".xlsm", "_export.xlsx", Len(ThisWorkbook.Path))
'The Len() is in case the File Path contains ".xlsm" for some reason
arrayOfSheetsToCopy = Array("originalSheet1", "originalSheet2", "originalSheet3")
With Workbooks.Add
.SaveAs fileName:=exportFileFullPath, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ThisWorkbook.Sheets(arrayOfSheetsToCopy).Copy after:=.Sheets(.Sheets.Count)
End With
End Sub
Final note: You are saving the file before you add the worksheets to it. Should those lines be the other way around?
This works for me
Sub export()
Dim myPath, folderPath, fileName, exportFileFullPath As String
Dim arrayOfSheetsToCopy As Variant
Dim sht As Worksheet
Dim newWorkBook As Workbook
folderPath = Application.ActiveWorkbook.Path
fullPath = Application.ActiveWorkbook.FullName
fileName = Replace(Application.ActiveWorkbook.Name, ".xlsm", "")
fileName = Replace(fileName, ".xlsx", "")
exportFileFullPath = folderPath & "\" & fileName & "_export.xlsx"
Set newWorkBook = Workbooks.Add
Call newWorkBook.SaveAs(fileName:=exportFileFullPath, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False)
For Each sht In ThisWorkbook.Sheets
Call sht.Copy(after:=newWorkBook.Sheets(Sheets.Count))
Next sht
Call newWorkBook.Close(saveChanges:=True)
End Sub
or if you want to use predefined sheetnames
For Each sheetName In Array("originalSheet1", "originalSheet2", "originalSheet3")
Call ThisWorkbook.Sheets(sheetName).Copy(after:=newWorkBook.Sheets(Sheets.Count))
Next sheetName

Access VBA - method or data member not found error

I'm new to Access and thank you for reading this first.
I'm exporting a query in Access to a pipe delimited CSV file. The query is from a table which is ODBCed from SQL.
I've been getting for the line dbs.Recordset : Method or data member not found error.
Huge thanks for any suggestion to fix this.
Option Compare Database
Option Explicit
Sub Command12_Click()
Dim dbs As DAO.database
Dim rst As DAO.Recordset
Dim intFile As Integer
Dim strFilePath As String
Dim intCount As Integer
Dim strHold
strFilePath = "C:\temp\TEST.csv"
Set dbs = CurrentDb
Set rst = db.OpenRecordset("T_Export_CSV", dbOpenForwardOnly)
intFile = FreeFile
Open strFilePath For Output As #intFile
Do Until rst.EOF
For intCount = 0 To rst.Fields.Count - 1
strHold = strHold & rst(intCount).Value & "|"
Next
If Right(strHold, 1) = "|" Then
strHold = Left(strHold, Len(strHold) - 1)
End If
Print #intFile, strHold
rst.MoveNext
strHold = vbNullString
Loop
Close intFile
rst.Close
Set rst = Nothing
MsgBox ("Export Completed Successfully")
End Sub
Thank you so so much for your time and please leave any comment below for any clarification if needed. I will try my best to be responsive!
Office 15.0 object library is the one you need to include in the references for O365 objects or Office 2013 Access VBA

Resources