Issue with worksheet object and LoadPicture in VBA - excel

I have been working on an excel macro and have come across an issue that doesn't make sense to me.
I have on two of my sheets, (Sheets("Printing Sheet") and Sheets("Printing Sheet B"), an Xactive image object called slipLogo. I created a subProcedure that should change the image loaded into slipLogo and the color of other cells on the sheet depending on an options selected within a userform. The userfrom also decides which of the two slipLogos and therefore sheets are being changed. But I was having problems with the image changing portion, so I pulled out the troublesome code to do some troubleshooting on it and focused on just one of the two sheets.
The issue is that I get the error "method failing" which points to the slipLogo part of ws.slipLogo.Picture=LoadPicture(C:Users\Logo.jpg). However when I use instead the following line Sheets("Printing Sheet").slipLogo.Picture=LoadPicture("C:\Users\Logo.jpg") everything works.
This indicates to me that for some reason ws does not equal Sheets("Printing Sheet").
Sub Help5()
Dim ws As Worksheet
Set ws = Sheets("Printing Sheet")
Dim imagePath As String
imagePath = "C:\Users\Logo.jpg"
ws.slipLogo.Picture = LoadPicture(imagePath)
'Sheets("Printing Sheet").slipLogo.Picture = LoadPicture(imagePath)
With Sheets("Printing Sheet").slipLogo 'the ws also does not work at this location
.Height = 35
End With
End Sub

Related

Sheet declaration goes wrong

I have been using vba for a while and i noticed an annoying bug.
When i use more than 1 sheets in a macro if i set the worksheets everything works just fine until i get an error. After that the worksheet names are messed up and usually uses both declaration for as one sheet.
Dim loc_path, sp_path As String
Dim loc_wb As Workbook
Dim sp_wb As Workbook
Dim loc_ws As Worksheet
Dim sp_ws As Worksheet
loc_path = "path1"
sp_path = "path2"
Set sp_wb = Workbooks.Open(sp_path, ReadOnly:=False)
Set sp_ws = sp_wb.Sheets(1)
Set loc_wb = Workbooks.Open(loc_path, ReadOnly:=False)
Set loc_ws = loc_wb.Sheets(1)
After that i just call another macro and pass the worksheet or sheets. In an example i pass only the sp_ws to the macro and display the first cells value in a msgbox. Before error it works fine, but after an error if i run it again it will display the loc_ws sheets first cells value.
Is there anything wrong with my code or it is just a bug in VBA?

In This Excel VBA Could some body tells me Why it refuses to take after parameter in the add method in worksheets object?

The code is:
Sub Copy_Filtered_Table()
Dim aSheet As Worksheet
Dim i As Long
i = ActiveSheet.Index
ActiveSheet.AutoFilter.Range.Copy
-> Set aSheet = ActiveWorkbook.Worksheets.Add(After:=i)
aSheet.Range("A1").PasteSpecial
End Sub
The workbook format is .xlsm Excel 2016
it has sheets after and before the active sheet
Also I Have tried doing it with out the aSheet variable like this
ActiveWorkbook.Worksheets.Add After:=i
It did not work too. both cases gives error 1004 Method 'Add' of object 'Sheet' faild.
If I ommited the After parameter it works but putting the result new sheet before the active sheet which exactly I am avoiding.
In order to insert relative to an existing sheet, you need to provide the actual sheet rather than its index, using one of:
Set aSheet = ActiveWorkbook.Sheets.Add(After:=ActiveWorkbook.Worksheets(i))
ActiveWorkbook.Sheets.Add After:=ActiveWorkbook.Worksheets(i)
Which one you choose depends on whether you immediately want to do something with the sheet without searching for it again but I suspect you already know that, given your question.
As an aside (though I haven't tried), I suspect getting the index of the current sheets then turning that back into the current sheet object is a bit unnecessary. You may want to just try:
Set aSheet = ActiveWorkbook.Sheets.Add(After:=ActiveWorkbook.ActiveSheet)

object required error 424 when copying a sheet from closed workbook

I got the rest of my other sub working the way I want it to. It just highlights cells of interest and hides rows that are irrelevant to me across a number of worksheets. One of the last manual processes for me in this is copying a worksheet into the report every day to run the sub. I finally got it working as a standalone sub:
Sub OrbitAdd()
Dim wbOrbit As Workbook
Dim wbTop As Workbook
Set wbTop = ActiveWorkbook
Set wbOrbit = Workbooks.Open("C:\Users\*****\Orbit.xlsx")
wbOrbit.Sheets(1).Copy after:=wbTop.Sheets(7)
wbOrbit.Close SaveChanges:=False
End Sub
When I went to incorporate this into the main sub is when it broke. I tried a basic Call OrbitAdd() and it threw an error (I forget which error). I think it was looking for some arguments to pass to the sub maybe? When I tried to copy this in there directly it would run and add the worksheet and close the workbook before throwing the object required 424 error. As far as I can tell it didn't do anything after closing the workbook.
Why is this working as an independent sub, and not no matter how I try to incorporate it into the main sub? What am I missing or need to do to transition from this block of code back to the main sub to handle the error? (the **** in the file path are to obscure irrelevant file path info)
edit: adding the next few lines from my main sub for further troubleshooting help. The only thing before the first shared code block is turning off screen updating and dimensioning parameters for the rest of the sub.
'sets Orbit range to the size of the eNodeB site list
With Sheet8
lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set Orbit = .Range("A1").Resize(lastRow, 1)
End With
'Clearing conditional formatting from the workbook.
For Each ws In ThisWorkbook.Worksheets
ws.Cells.FormatConditions.Delete
Next ws
'iterates each worksheet with the tables to apply the formatting.
For j = 1 To 3
If j = 1 Then
Set ws = Sheet2
ElseIf j = 2 Then
Set ws = Sheet3

How to hide columns in a VBA named range?

I'm pretty new to VBA and I'm trying to hide some columns in workbooks.
I have to do it in VBA because the workbook is an Analysis for Office workbook, so I have to hide some columns that the final users don't have to see.
My problem is that I can't point to a specific letter of the columns, because, since the workbook is modifiable like a pivot with other dimensions in respect of the default ones with which it opens, if I point to a specific column in the code, it won't be the same when an user add new dimensions. So I have to find the column with its name ad hide it.
So for now I tried this:
Sub Hide_Columns()
'Dim Sourcecell As Range
Dim wb As Workbook
Dim ws As Worksheet
'Set Sourcecell = Nothing
'Set Sourcecell = ThisSheet.Range("SapCrosstab1").Find("Colonna di calcolo", LookIn:=xlFormulas)
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Demand Planning")
wb.Sheets("Demand Planning").Range("Colonna di calcolo").EntireColumn.Hidden = True
End Sub
The problem here is that I'm having the
"Run-time error 1004: Application-defined or object-defined error"
and I don't know how to fix it.
I commented that 3 lines because I'm not so sure they could help.
Your current attempt fails because Range("Colonna di calcolo") will not search for a column with that header. Instead, it want to access a Named Range with that name, and if you don't define this, it will throw exactly this error 1004.
I think your attempt with SourceCell was not bad - issue a Find command and hide the EntireColumn of the found cell. Your mistake was that there is no object ThisSheet. There are objects ThisWorkbook which refers to the entire workbook where the code is stored, or ActiveWorkbook which is the Workbook that is currently shown (not necessarily the workbook where the macro is stored).
You can solve your issue either by defining a Named Range for the column - in that case your code should work.
Or change the code to something like
Dim ws as Worksheet
Set ws = ThisWorkbook.Sheets("Demand Planning")
Dim Sourcecell as Range
Set Sourcecell = ws.Range("1:1").Find("Colonna di calcolo", LookIn:=xlFormulas)
If Not Sourcecell Is Nothing Then
Sourcecell.EntireColumn.Hidden = True
End If

VBA: Paste ceases to work (suddenly) in specific macro

I'm a very new, self-taught programmer, so please keep this in mind in your responses. I have extensively searched this and other forums and can't seem to find a similar question.
The following code has been working for weeks and has not been changed. (My macro includes more variables and code, but I know from taking it apart that those pieces work, so I've left them out for clarity). From what I can tell the PasteSpecial function is specifically not working.
Dim StimSheet As String
ActiveCell.Rows("1:290").EntireRow.Select
Selection.Copy
'Copies the data for the current stimulus
StimSheet = Application.InputBox("Enter the name of the stimulus")
'asks name of the stimulus
Sheets.Add After:=Worksheets(Worksheets.Count)
ActiveSheet.Name = StimSheet
'adds new sheet at the end and names whatever you input as stimulus name
Sheets(StimSheet).Select
Selection.PasteSpecial Paste:=xlPasteValues
'pastes data into new sheet
At this point there is no error, the macro simply stops after copying and creating the new sheet.
Here's what I know / have tried:
The macro is successfully making and naming the new sheet and copying the selection to the clipboard, because I can manually paste it after running the macro. It seems to be getting stuck at the paste piece.
Other macros that use the exact same format of copy / paste special are still working correctly.
Another forum with a similar program suggested typing "Application.EnableEvents=True" into the immediate window. This did not change anything.
This macro has worked for several weeks with no errors. I have made new macros using previously saved code in case something inadvertently was changed in the current one, but this did not work either.
The paste option will work one time on a new file and then ceases to work again.
Thank you in advance for your suggestions.
You might find the problem is that you don't have much control over which workbook and worksheet this code applies to. It's better to avoid ActiveSheet, Select, and Sheet with no parent as much as you can.
If you only need to copy the values of cells without any formatting, then Paste isn't needed either.
Try changing your code to the following and see if you have any better luck:
Const BOOK_NAME As String = "Book1.xlsm" 'change this to your workbook name
Const SOURCE_SHEET_NAME As String = "Sheet1" 'change this to your sheet name
Dim wb As Workbook
Dim sourceSheet As Worksheet
Dim newSheet As Worksheet
Dim newSheetName As String
Dim validName As Boolean
Dim rng As Range
' Set the book, sheet and range objects
Set wb = Workbooks(BOOK_NAME)
Set sourceSheet = wb.Worksheets(SOURCE_SHEET_NAME)
Set newSheet = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
' Acquire the new sheet name and check it's valid.
Do
newSheetName = InputBox("Enter the name of the stimulus")
On Error Resume Next
newSheet.Name = newSheetName
validName = (Err.Number = 0)
On Error GoTo 0
If Not validName Then MsgBox "Sheet name isn't valid. Try again."
Loop Until validName
' Write the values into the new sheet
Set rng = sourceSheet.Cells(1, 1).Resize(290, sourceSheet.UsedRange.Columns.Count)
newSheet.Range(rng.Address).value = rng.Value2
I moved this line:
StimSheet = Application.InputBox("Enter the name of the stimulus")
to the top of the method and it seems to work reliably. I wish I could tell you exactly why, but at least you can proceed. Perhaps it has something to do with the focus changing.
Also, when it failed for me (Office 2013) I got the following error:
Run-time error 1004:
Application-defined or object-defined error.
When the Sub was in a Sheet code behind, and this:
Run-time error '1004'
PasteSpecial method of Range class failed.
When pasted in a Module.

Resources