cannot identify Workbook as object variable - excel

I'm building an automated request form and am running into a headache that only triggers for other users. 3 others receive a run-time error and I cannot figure out what is going on as I've used basically this same script in other books without ever having an issue reported.
Sub tracker_upload()
ActiveWindow.ScrollRow = 1
Run "processing" 'basic UF to display status
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
Run "archive" 'saves completed form to a SP folder
With WaitForm
.lbStatus.Caption = "...archiving form to shared drive"
.Repaint
End With
Application.Wait (Now + TimeValue("00:00:02"))
With Form
If .Priority_Critical_YN = True Then
p = "Critical"
ElseIf .Priority_Must_Have_YN = True Then
p = "High"
ElseIf .Priority_Need_YN = True Then
p = "Medium"
ElseIf .Priority_Nice_YN = True Then
p = "Low"
End If
.Shapes("upload").Visible = False
End With
With Range("tbData")
uID = .Cells(1).Value
.Cells(2) = "New"
.Cells(3) = p
.Cells(9) = Environ$("UserName")
.Cells(10) = Date
.Hyperlinks.Add .Cells(1), ThisWorkbook.FullName, TextToDisplay:=uID
End With
With WaitForm
.lbStatus.Caption = "...updating tracker information"
.Repaint
End With
Dim wb1 As Workbook, wb2 As Workbook
On Error Resume Next
Set wb1 = ActiveWorkbook
Set wb2 = Workbooks("Requests Tracker")
'detect if workbook is already open and open if not
If wb2 Is Nothing Then
Application.Workbooks.Open ("My Shared Drive Location\Requests Tracker.xlsx"), ignorereadonlyrecommended = True
Set wb2 = Workbooks("Requests Tracker")
End If
On Error GoTo 0
wb1.Sheets("data").Range("tbData").Copy
With wb2
.Activate
With .Sheets("Requests")
If .Range("tbTracker").Cells(1) = "" Then
lastrow = .Range("A" & Rows.Count).End(xlUp).Row
Else: lastrow = .Range("A" & Rows.Count).End(xlUp).Row + 1
End If
.Range("A" & lastrow).PasteSpecial xlPasteAllUsingSourceTheme
.Columns.AutoFit
End With
.Save
.Close True
End With
Set wb2 = Nothing
On Error GoTo 0
With Application
.CutCopyMode = False
.ScreenUpdating = True
.DisplayAlerts = True
.Wait (Now + TimeValue("00:00:02"))
End With
Unload WaitForm
wb1.Save
mb = MsgBox("This request has been successfully recorded on the Tracker" & vbCrLf _
& vbCrLf _
& "The form will now close, would you like to open the tracker now?", vbYesNo + vbInformation, "completed")
If mb = vbYes Then
Application.Workbooks.Open ("My Shared Drive Location\Requests Tracker.xlsx"), ignorereadonlyrecommended = True
End If
If Application.Windows.Count = 1 Then
wb1.Saved = True
Application.Quit
Else: wb1.Close False
End If
End Sub
initially it was getting hung up on the .Sheets("Requests") line, then the line below it. It was the decimal in front of each, which I found really bizarre as I've never come across this before. Sure enough, after leaving the .Save and .Close True with decimals, it triggered another error on the next function preceded by a decimal as shown below.
UPDATE: I parsed out the bit of code where I set wb1 and wb2 as I identified it was wb2 that was giving the user an error. I did some testing with several other users who had no issue setting & identifying wb2 as Workbooks("Requests Tracker"). I finally got the sub to pass by adding the file extension to the end of the Workbook name. Why would this be required for this user only?

I had to specify set wb2 = "Requests Tracker.xlsx" in order for the user to not hit a run-time error. I do not know why .xlsx had to be added for this one user and no one else in the entire department...but that resolved the headache.

Related

How do I apply Macro/ VBA code in the all worksheets for all workbooks in a folder?

I am trying to apply one code to all my worksheets in a folder. This is the code I use for one workbook and it can only function in one workbook therefore even if I shared it to another workbook it will only apply to the workbook that has the code. How can I change to make it work? This is the one that I tried but it was not able to run.
If fDialog.Show = -1 Then
folderName = fDialog.SelectedItems(1)
End If
'Create a separate Excel process that is invisibile
Set eApp = New Excel.Application: eApp.Visible = False
'Search for all files in folder [replace *.* with your pattern e.g. *.xlsx]
fileName = Dir(folderName & "\*.*")
Do While fileName <> ""
'Update status bar to indicate progress
Application.StatusBar = "Processing " & folderName & "\" & fileName
Set wb = eApp.Workbooks.Open(folderName & "\" & fileName)
Cells.Select
With Selection.Font
.Name = "Arial"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
wb.Close SaveChanges:=False 'Close opened worbook w/o saving, change as needed
Debug.Print "Processed " & folderName & "\" & fileName
fileName = Dir()
Loop
eApp.Quit
Set eApp = Nothing
'Clear statusbar and notify of macro completion
Application.StatusBar = ""
MsgBox "Completed executing macro on all workbooks"
I have no basic in VBA coding, please help. Thanks
I found this and it works, but it would still be helpful if anyone could make the one I initially posted works. Thank you
Sub LoopFormat()
Dim wb As Workbook, MyPath, MyTemplate, MyName
Dim ws As Worksheet
MyPath = "C:\Folder\"
MyTemplate = "*.xlsx"
MyName = Dir(MyPath & MyTemplate)
Do While MyName <> ""
Set wb = Workbooks.Open(MyPath & MyName)
For Each ws In wb.Worksheets
ArialForAll
Next ws
wb.Close True
MyName = Dir()
Loop
End Sub
Sub ArialForAll()
With ws
Cells.Select
With Selection.Font
.Name = "Arial"
.Size = 10
End With
End With
End Sub
I see two changes you could make that may help your original code:
fileName = Dir(folderName & "\*.xlsx")
wb.Close SaveChanges:=True
Note that these suggestions were noted in the comments, so, documentation is important to read, though it's not always helpful.

Asked to Enable Macros In a Workbook Without Them

The macro copies over the sheets to a newly created workbook, I send this report that is WITHOUT MACROS.
However, my client says she has to open the file to enable macros and then re-save.
She says she has a "file linked to the report," so prob. a program that pulls data from the closed report.
She also sent me a photo of her screen with the little yellow bar prompting her that the file is in protected view.
Is there any reason in my code that explains this situation?
Here is my code:
Sub Generate_Position_Report()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.Calculate
Do While Application.CalculationState <> xlDone
DoEvents
Loop
''''''''' Open Previous Report '''''''''
Dim d As Date
d = DateAdd("d", -1, Date)
Dim d3 As Date
d3 = d - 2
Dim prev_file As String
Dim prev_file_exists As String
prev_file = "X:\Risk\Departmental\Reporting\Position Report " & Format(d, "yyyy-mm-dd") & ".xlsx"
prev_file_exists = Dir(prev_file)
If prev_file_exists <> "" Then
Workbooks.Open Filename:="X:\Risk\Departmental\Reporting\Position Report " & Format(d, "yyyy-mm-dd") & ".xlsx"
Else
Workbooks.Open Filename:="X:\Risk\Departmental\Reporting\Position Report " & Format(d3, "yyyy-mm-dd") & ".xlsx"
End If
ThisWorkbook.Activate
''''''''' Variables '''''''''
sim_date = Range("SIM_DATE").Value
main_analysis_name = Range("MAIN_ANALYSIS_NAME").Value
secondary_analysis_name = Range("SECONDARY_ANALYSIS_NAME").Value
previous_workday = Range("PREVIOUS_WORKDAY").Value
t_minus_2_workday = Range("T_MINUS_2_WORKDAY").Value
previous_day_quotes = Range("PREVIOUS_DAY_QUOTES").Value
t_minus_2_quotes = Range("T_MINUS_2_DAY_QUOTES").Value
price_curves_analysis = Range("PRICE_CURVES_ANALYSIS").Value
previous_analysis_date = Range("PREVIOUS_ANALYSIS_DATE").Value
previous_analysis_name = Range("PREVIOUS_ANALYSIS_NAME").Value
col_shift = Range("COL_SHIFT").Value
Application.DisplayAlerts = False
''''''''' Recalculate Data '''''''''
Application.Calculate
Do While Application.CalculationState <> xlDone
DoEvents
Loop
'''''''''' Save the Template ''''''''''
'good practice to turn things back on for the template'
Application.DisplayAlerts = True
Application.ScreenUpdating = True
ThisWorkbook.Save
'we need to turn them off again to finalize the report'
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'''''''''' Copy/Paste Values ''''''''''
'we need to copy and paste values for all the worksheets'
For Each ws In Worksheets
Sheets(ws.Name).Activate
Sheets(ws.Name).Cells.Copy
Sheets(ws.Name).Cells.PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Sheets(ws.Name).Cells(1, 1).Select
Next
'''''''''' Create Fresh Copy Without Macros ''''''''''
ThisWorkbook.Sheets.Copy
Application.DisplayAlerts = False
Application.ScreenUpdating = False
ActiveWorkbook.SaveAs Filename:="X:\Risk\Departmental\Reporting\Position Report (TEST) " & Format(d + 1, "yyyy-mm-dd") & ".xlsx", FileFormat:=51
'physically breaking links'
Dim wb As Workbook
Set wb = Application.ActiveWorkbook
If Not IsEmpty(wb.LinkSources(xlExcelLinks)) Then
For Each link In wb.LinkSources(xlExcelLinks)
wb.BreakLink link, xlLinkTypeExcelLinks
Next link
End If
'''''''''' Activate/Hide/Delete Tabs ''''''''''
Worksheets("Control").Visible = False
Worksheets("Reference").Visible = False
Worksheets("HERITAGE Summary").Activate
'turning back on some features for the active/report'
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
ActiveWorkbook.Save 'saving the report'
Workbooks(2).Close 'closes the prev. file'
ThisWorkbook.Close savechanges:=False 'closes the template'
End Sub

Error 440 After I add application.displayalerts = false

When I add Application.DisplayAlerts = false and Application.DisplayAlerts = True either side of sheets("Sheet2").Delete I get the 440 error.
Not sure what the issue is but it runs no problem without the application.displayalerts.
I have been googling for ages I have tried a couple things mentioned on other questions posted on here. I feel like maybe i need another line of code or something.
Code that isnt working:
Private Sub CommandButton1_Click()
Dim numberCopies As Long
Dim currentRow As Long
Dim j As Long
Dim sht As Worksheet
Set sht = Sheets("sheet3")
currentRow = 2
Do While Not IsEmpty(sht.Cells(currentRow, 1))
numberCopies = sht.Cells(currentRow, 1)
For j = 2 To numberCopies
sht.Rows(currentRow).Copy
sht.Rows(currentRow).Insert Shift:=xlDown
currentRow = currentRow + 1
Next j
currentRow = currentRow + 1
Loop
Application.CutCopyMode = False
sht.Columns(1).Delete
Dim Path As String
Dim Filename1 As String
Dim Filename2 As String
Path = ThisWorkbook.Path & "\"
Filename1 = Range("B1")
Filename2 = Range("D1")
Application.DisplayAlerts = False
Sheets("Sheet2").Delete
Sheets("Sheet1").Delete
Application.DisplayAlerts = True
ActiveWorkbook.SaveAs Filename:=Path & Filename1 & "-" & Filename2 & ".csv", FileFormat:=xlCSV
MsgBox "This usage file as been saved in the same folder as the Usage Upload Creator, it is saved as " & ActiveWorkbook.Name & " This workbook will now close and you can upload your usage file on CPQ. Thank You."
ActiveWorkbook.Close False
End Sub
I just dont want the "are you sure you want to delete the sheet" alert popping up.
Worked out in the comments what the problem was, The problem is that you cannot have the ActiveX button on the sheet that you're trying to delete. You can supress the error and alerts by using this:
On Error Resume Next
Application.DisplayAlerts = False
Sheets("Sheet2").Delete
Sheets("Sheet1").Delete
Application.DisplayAlerts = True
On Error GoTo 0

Export SAP Data won't open workbook while running

I wrote a code to export data from SAP to an Excel workbook. To do that I open the transaction (IW28 in this case), export the file and save it to a specified location. When the file is opened, I want to copy the data from the exported sheet to my own sheet.
The problem is that the exported sheet won't open while I'm running the macro. When I add a breakpoint in my code, the exported sheet opens when the macro stops. Without this breakpoint the exported sheets only opens after the macro had finished.
'Laden van de data uit transactie IW28 naar de sheet
Dim lastcolumn As Long
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'SAP Variant
SapVariant = "Variant"
'Transaction
Name = IW28
'Current File Location
Map = Application.ActiveWorkbook.Path
If Not IsObject(SapApp) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set SapApp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = SapApp.Children(0)
End If
If Not IsObject(session) Then
Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject SapApp, "on"
End If
'Check if file is already open, if so then close the file
If IsOpen(Name & ".xlsx") = True Then Workbooks(Name & ".xlsx").Close
'Open Transaction
session.findById("wnd[0]/tbar[0]/okcd").Text = "/N" & Name
session.findById("wnd[0]").sendVKey 0
'Choose Variant
On Error Resume Next
session.findById("wnd[0]/mbar/menu[2]/menu[0]/menu[0]").Select
session.findById("wnd[1]/usr/txtV-LOW").Text = SapVariant
'Check if variant excists
If Not Err.Number = 0 Then
VarMsgbox = MsgBox("Selecteer variant " & SapVariant & ", dubbelklik om deze te selecteren en klik dan hieronder op ok (niet eerder!)", vbOKCancel, "Selecteer variant")
If VarMsgbox = vbCancel Then Exit Sub
Else
session.findById("wnd[1]/usr/txtENAME-LOW").Text = ""
session.findById("wnd[1]/usr/txtV-LOW").caretPosition = 10
session.findById("wnd[1]").sendVKey 0
session.findById("wnd[1]").sendVKey 8
End If
'Execute Variant
session.findById("wnd[0]").sendVKey 8
'Select all data in SAP
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").SelectAll
'Export to Excel
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectContextMenuItem "&XXL"
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Add filename and path
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = Name & ".xlsx"
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = Map
session.findById("wnd[1]/tbar[0]/btn[11]").press
'Determine lastrow of sheet
Lastrow = Workbooks(Name & ".xlsx").Sheets("Sheet1").Range("B99999").End(xlUp).Row
ThisWorkbook.Sheets(Name).Range("A8:C99999").ClearContents
Workbooks(Name & ".xlsx").Sheets("Sheet1").Range("A2:C" & Lastrow).Copy
ThisWorkbook.Sheets(Name).Range("A8").PasteSpecial xlPasteValues
ThisWorkbook.Sheets("Start").Activate
Application.DisplayAlerts = True
Application.ScreenUpdating = True
You could try the following program construction:
Public Name as String
Sub Makro1()
'Laden van de data uit transactie IW28 naar de sheet
Dim lastcolumn As Long
. . .
session.findById("wnd[1]/tbar[0]/btn[11]").press
call Makro2
End Sub
Sub Makro2()
'Determine lastrow of sheet
Lastrow = Workbooks(Name & .xlsx").Sheets("Sheet1").Range("B99999").End(xlUp).Row
ThisWorkbook.Sheets(Name).Range("A8:C99999").ClearContents
Workbooks(Name & ".xlsx").Sheets("Sheet1").Range("A2:C" & Lastrow).Copy
ThisWorkbook.Sheets(Name).Range("A8").PasteSpecial xlPasteValues
ThisWorkbook.Sheets("Start").Activate
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Remove filter in Excel form an imported Access data file in VBA

I import from Access to Excel a data (tables) file, but I don't manage to remove the filter. I get a 1004 error (Delete of Range is failed). I also can't remove it by hand.
Sub Openaccessdatafile()
'Niet blad updaten
Application.ScreenUpdating = False
Sheets.Add.Name = "Gegevens alginaten"
Set sh = ThisWorkbook.Sheets("Gegevens alginaten")
LR = sh.Cells(Rows.Count, "A").End(xlUp).Row
Filename = Application.GetOpenFilename("Excel files (*.xls*), *.xls*")
MsgBox Filename
If Filename <> False Then
Workbooks.Open (Filename)
ActiveSheet.UsedRange.Copy sh.Range("A" & LR)
ActiveWorkbook.Close
Sheets("Start").Cells(2, 5).Value = "Ok"
Else
MsgBox "Geen bestand aangeklikt."
Application.DisplayAlerts = False
Sheets("Gegevens alginaten").Delete
Application.DisplayAlerts = True
End If
'Wel blad updaten
Application.ScreenUpdating = True
Sheets("Start").Select
End Sub
Apparently exporting it with Access through a VBA macro button does work better. Than I could remove the row, because the filter is than not added in the exported file.

Resources