I have some VBA code which I use in another workbook to resize a table to be 1 row and delete the contents of a data table to initialize a workbook. Then a file prompt opens asking the user to select the appropriate file for processing. For some reason, I am getting a
"Run-time error '91': Object variable or With block variable not set"
The code is a copy and paste from the other workbook and I have adjusted the names of the variables, workbooks, worksheets, and table names.
workbook is called "IMD Processing.xlsm" with 2 sheets titled "IMD" and "Raw". The "Raw" sheet has a table with the name "tbl_raw" and the "IMD" sheet has a table with the name "tbl_imd".
Any guidance would be greatly appreciated.
Option Explicit
Sub IMDAutomation()
Dim fileName As String 'Filename string
Dim wb_macro As Workbook 'Macro workbook
Dim ws_macro_imd As Worksheet 'Macro worksheet
Dim ws_macro_raw As Worksheet 'Macro raw worksheet
Dim wb_imd As Workbook 'IMD Workbook for processing
Dim ws_imd As Worksheet 'IMD Worksheet for processing
Dim objTable As ListObject 'Table of raw data
Dim tbl_raw As ListObject 'Raw table in macro workbook
Dim tbl_imd As ListObject 'IMD table in macro workbook
Dim vals As Variant 'Array to store values
Dim lrow As Long 'Variable used to determine number of rows in data table
Set wb_macro = ThisWorkbook
Set ws_macro_imd = Sheets("IMD")
Set ws_macro_raw = Sheets("Raw")
'============ Initialize macro workbook - clearing data ============'
'Clear the raw data in the macro workbook
Set tbl_raw = ws_macro_raw.ListObjects("tbl_raw")
With tbl_raw.DataBodyRange
If .Rows.Count > 1 Then
.Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count).Rows.Delete
End If
End With
tbl_raw.DataBodyRange.Rows(1).ClearContents
'Clear the IMD data in the macro workbook
Set tbl_imd = ws_macro_imd.ListObjects("tbl_imd")
With tbl_imd.DataBodyRange
If .Rows.Count > 1 Then
.Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count).Rows.Delete
End If
End With
'============ Locate Raw Data File ============'
'Open file dialog to locate the Workforce Review raw data workbook exported from system
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "Select the IMD file"
.Filters.Clear
.Filters.Add "Custom Excel Files", "*.xlsx, *xls, *csv"
.Show
fileName = .SelectedItems.Item(1)
End With
If InStr(fileName, ".xlsx") = 0 Then
Exit Sub
End If
Workbooks.Open fileName
'Set the Workforce Review raw workbook
Set wb_imd = ActiveWorkbook
'Set the worksheet
Set ws_imd = wb_imd.ActiveSheet
lrow = ws_imd.Cells(ws_imd.Rows.Count, 2).End(xlUp).Row
vals = ws_imd.Range("A2:CU" & lrow)
Application.CutCopyMode = False
Application.CutCopyMode = True
End Sub
UDPATE WITH SOLUTION
Thanks to #Variatus for the solution.
I did not have a data row in my table so I created one and now it's working.
This should work to handle cases where there is no row in the table. If tbl_raw.DataBodyRange Is Nothing Then InsertRowRange Else (Code to clear the table)
Probably the object that is being searched for by Set tbl_raw = ws_macro_raw.ListObjects("tbl_raw") does not exist in the new workbook and hence referencing through With tbl_raw returns this error
Related
I have a series of Workbooks that I continually need to copy Sheet1 of a workbook to Sheet2 of the new workbook. The names of the Workbooks will advance in number (name_May2011_2, name_May2011_3, name_May2011_5). The digit on the end will change, not necessarily in sequence. I have code that allows me to list the active workbooks in a new sheet. I need to reference a cell in that sheet as the name of the Workbook as the destination top copy. My code is as follows so far:
[code]
Sub Copy_Merge()
'Declare variables and data types
Dim Wb As Workbook
Dim Ws As Worksheet
Dim i As Single, j As Single
'Create a new worksheet and save to object ws
Set Ws = Sheets.Add
'Go through open workbooks
For j = 1 To Workbooks.Count
'Save workbook name to cell A1 and downwards
Range("A1").Cells(j, 1) = Workbooks(j).Name
'Iterate through worksheets in given workbook
For i = 1 To Workbooks(j).Sheets.Count
'Save worksheet names to cell B1 and cells further right
Range("A1").Cells(j, i + 1) = Workbooks(j).Sheets(i).Name
'Continue with next worksheet
Next i
'Continue with next workbook
Next j
'This is the part I'm having issues with
'I need to set variable in cell A2 of Sheet 2 of Active Workbook as a string
'and use that string as the Workbook destination name
Dim SB As Workbook
Dim Ss As Worksheet
Set SB = ThisWorkbook
Set Ss = ThisWorkbook.Sheet("Sheet2")
Set MyToday = SB.Ss.Range("A2").Value 'name of destination workbook
Sheets("Sheet1").Select
Sheets("Sheet1").Copy Before:=Workbooks(MyToday).Sheets(3)
On Error Resume Next
ActiveSheet.Name = "Sheet2"
On Error GoTo 0
End Sub
[/code]
I've been working on this for a few days, I'm relatively new to writing macro's, and I'm at my whit's end. Can someone help with this code or suggest a better code to use?
In order to retrieve the target workbook's name from cell "A2" of "Sheet2" of your current workbook and use it to assign the respective workbook to an object, you could use:
Dim SourceWorkbook As Workbook ' Your SB
Dim SourceWorksheet As Worksheet ' Your Ss
Dim TargetWorkbook As Workbook
Dim TargetWorksheet As Worksheet
Dim TargetWorkbookName As String
Dim TargetSheetName As String
Set SourceWorkbook = ThisWorkbook
Set SourceWorksheet = SourceWorkbook.Sheets("Sheet2") ' the "s" in "Sheets" is important to access the Workbook's Sheet-Collection
TargetWorkbookName = SourceWorksheet.Range("A2").Value ' TargetWorkbookName is of type "String", thus "Set" is not allowed
Set TargetWorkbook = Workbooks(TargetWorkbookName)
TargetSheetName = SourceWorksheet.Range("B2").Value
Set TargetWorksheet = TargetWorkbook.Sheets(TargetSheetName)
new to VBA and copying data from one worksheet and posting it into another the user select the source file and it copies the data from the sheet and post it into the destination file where the data values in the source file does not remain the same size
I've tried creating different variable to be used to store the worksheet data but that was unsuccessful and it also said the error was because some data values were protected when I debugged it but I unlocked the sheets and still get the same error
Private Sub CommandButton1_Click()
Dim source As Workbook
Dim sht1 As Worksheet
Dim destination As Workbook
Dim sht2 As Worksheet
Dim tmp As String
Dim startCell As Range
Dim lastRow As Long
Dim lastColumn As Long
setFile = Application.GetOpenFilename 'used to open the browser window
tmp = setFile 'store the selected file in variable tmp
Application.ScreenUpdating = False 'preventing long runtimes
If Dir(tmp) <> "" Then
Set source = ThisWorkbook 'workbook b1 is declared as the current worksheet opened
Set destination = Workbooks.Open(tmp) 'the file the user selected is opened in excel
Set sht1 = destination.Sheets("L1 OVERVIEW")
Set sht2 = source.Sheets("Overview Paste")
Set startCell = Range("D5")
sht1.Activate
'find last rown and last column
lastRow = sht1.Cells(sht1.Rows.Count, startCell.Column).End(xlUp).Row
lastColumn = sht1.Cells(startCell.Row, sht1.Columns.Count).End(xlToLeft).Column
sht1.Range(startCell, Cells(lastRow, lastColumn)).Select 'select range
sht1.Copy 'copy all the data in selected sheet
sht2.Range("D5").PasteSpecial xlPasteAll
Application.CutCopyMode = False
destination.Close True
Else 'used to prevent a error message from popping up when the user choose to cancel selecting a file
End If
End Sub
I am expecting the data to be automated where it copies the data from the source worksheet and paste it into the destination worksheet which has all the calculations and cells are in the same order as the values it was copied from. which I could use for simulations
I currently have a master workbook that I use to create external pdf forms. My current code lets me browse to a folder and select another workbook to pull specific data from and paste it into the Master.
The data is copied from external workbook, sheet1, and pasted to active workbook, sheet1. The code I am working with is "For Each Sheet." Works like a charm.
The problem is that I have added another sheet to the workbooks and it's throwing a Run-time error 1004. I need to recode it so it copies from only sheet1 in the external workbook and pastes only to sheet1 of the Master (active).
Any ideas? Thanks for any help you can pass along.
Sub ImportData()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sheet As Worksheet
Dim PasteStart As Range
Dim sh As Worksheet
Dim strXLSFile As String, strPDFFile As String, strFolder As String
strFolder = "H:\Company Data\Firm Files\Client Data Workbooks\Excel Data-Client Info"
Set wb1 = ActiveWorkbook
Set PasteStart = [Client_Data]
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xlsm (*.xlsm),")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
For Each Sheet In wb2.Sheets
With Sheet.Cells.Range("B9:B27")
.Copy PasteStart
Set PasteStart = PasteStart.Offset(.Rows.Count)
End With
Next Sheet
End If
wb2.Close False
End Sub
if you only want Sheet1 then get rid of the loop.
Instead of:
For Each Sheet In wb2.Sheets
With Sheet.Cells.Range("B9:B27")
.Copy PasteStart
Set PasteStart = PasteStart.Offset(.Rows.Count)
End With
Next Sheet
Try:
wb2.sheets(1).range("B9:B27").copy PasteStart
it seems like this is a one time use so no need to Set PasteStart = again. Hope this helps
I am looking for a macro to paste some data onto a moving range. I already have a cell that tells me the number of the next non empty column and this is the code I currently use:
Dim OpenFileName As String
Dim wb As Workbook
'Select and Open workbook
OpenFileName = Application.GetOpenFilename()
If OpenFileName = "False" Then Exit Sub
Set wb = Workbooks.Open(OpenFileName)
'Get data EXAMPLE
ThisWorkbook.Sheets("Teleselling 17").Range("I9:I289")*this should be dynamic, I want to paste data in a moving range*.Value = wb.Sheets("TELESELLING INBOUND").Range("L9:L289").Value
wb.Close SaveChanges:=False
MsgBox ("Done!")
Use the newly opened workbook/worksheet/range to define the scope of the value transfer.
with wb.workSheets("TELESELLING INBOUND").Range("L9:L289")
ThisWorkbook.workSheets("Teleselling 17").Range("XFD9").end(xltoleft).offset(0, 1).resize(.rows.count, .columns.count) = .value
end with
Yet another worksheet copying problem! This is a simple problem that has got me stumped. I want the click of a command button (in action.xlsm) to repopulate the values in a range ("stock" - 2 cols & maybe 100 rows - this is the master inventory records) in a separate excel file (inventory.xlsx), from a named range ("newInventory" - same size as other named range) in the active worksheet (in action.xlsm) that has had the original "stock" values reduced by the values of items taken out of stock. The calculations are OK I just can't get the master inventory file to update. I have checked heaps of forums and tried two approaches to no avail. I have tried:
Private Sub CommandButton1_Click()
Dim InventoryFileName As String
InventoryFileName = "C:\Users\david\Documents\inventory.xlsx"
Workbooks(InventoryFileName).Worksheets("Sheet1").Range("stock") = ThisWorkbook.Worksheets("inventory").Range("newInventory").Value
Workbooks(InventoryFileName).Save
End Sub
Throws a "Run-time error '9': Subscript out of range" on line 4. I have also tried:
Private Sub CommandButton1_Click()
Dim wbTarget As Workbook 'workbook where the data is to be pasted
Dim wsTarget As Worksheet
Dim wbThis As Workbook 'workbook from where the data is to copied
Dim wsThis As Worksheet
Dim strName As String 'name of the source sheet/ target workbook
'set to the current active workbook (the source book)
Set wbThis = ActiveWorkbook
Set wsThis = ActiveSheet
'get the active sheetname of the book
strName = wsThis.Name
'open a workbook that has same name as the sheet name
Set wbTarget = Workbooks.Open("C:\Users\david\Documents\" & strName & ".xlsx")
Set wsTarget = wbTarget.Worksheets("Sheet1")
'select cell A1 on the target book
wbTarget.wsTarget.Range("A1").Select
'clear existing values form target book
wbTarget.wsTarget.Range("A1:B10").ClearContents
'activate the source book
wbThis.Activate
'clear any thing on clipboard to maximize available memory
Application.CutCopyMode = False
'copy the range from source book
wbThis.wsThis.Range("A1:B10").Copy
'paste the data on the target book
wbTarget.wsTarget.Range("A1").PasteSpecial Paste:=xlPasteValues
'clear any thing on clipboard to maximize available memory
Application.CutCopyMode = False
'save the target book
wbTarget.Save
'close the workbook
wbTarget.Close
'activate the source book again
wbThis.Activate
'clear memory
Set wbTarget = Nothing
Set wbThis = Nothing
End Sub
This throws a "Run-time error '438': Object doesn't support this property or method" on line wbTarget.wsTarget.Range("A1").Select
What have I got wrong? Any suggestions?
Replace
wbTarget.wsTarget.Range("A1").Select
with just
wsTarget.Range("A1").Select
The workbook is already implied from the way you defined wsTarget. I suspect that will do it. If you run the code in the debugger, then when you do a "watch" on the variable you can see exactly what does and doesn't work..
Firstly you have 2 commandbutton1. Secondly you must have a reference for a Range like:
Workbooks(InventoryFileName).Worksheets("Sheet1").Range("A3:B21") = ThisWorkbook.Worksheets("inventory").Range("A10:B12").Value
or
stock="A3:B21"
newInventory="A10:B12"