Why is defined range not working with End(xlDown).Select? - excel

I am running a function with a defined range and when trying to use End.(xlDown).Select I get a message "Select method of Range class failed".
I have edited the code below to show only the problem piece. After literally two hours of trying everything, I cannot get it to work.
The annoying part is that I have to use defined ranges since the function is part of a much larger Sub that doesn't work as intended once Select and Activate are used.
Function OutputFunction()
Dim rng8 As Range
Set rng8 = ThisWorkbook.Worksheets(5).Range("A2")
rng1.ClearContents 'Works like a charm.
rng2.Copy 'No problem here either.
rng8.End(xlDown).Select 'Fails misserably.
ActiveCell.Offset(0, 13).Select
Range(Selection, Range("N3")).Select
ActiveSheet.Paste

rng2.Copy destination:= rng8.parent.range(rng8.End(xlDown).Offset(0, 13), rng8.parent.Range("N3"))
"After literally two hours of trying everything, I cannot get it to work."
The first rule of Excel Macros: Never, ever, use SELECT in an Excel Macro.
The second rule of Excel Macros: Don't use Select in Excel Macros
The third.....

Try:
Option Explicit
Sub test()
Dim rng8 As Range
'Have in mind that you refer to a sheet based on it s index, NOT with its name!
'If sheets order change you will refer to another sheet
With ThisWorkbook.Worksheets(5)
Set rng8 = .Range("A2")
rng8.Select
.Range(rng8, rng8.End(xlDown)).Select
End With
End Sub

Try to use End(xlDown).Select in my personal macro. First I tested this in the original excel file that I wrote the macro in, and it worked in every step just fine. But the problem occurred when I used it in another file.
After some tests, I changed the .Select with .Activate and it worked. I'm not 100% sure whether we are talking on the same page or not, so tell me if this solved your problem, so I can improve my answer.

Related

Why Is My Spreadsheet Showing Ghost Images From Another Worksheet After Running My Script

(07/08/21 - I edited my text to update and sharpen the problem).
I have made an Excel VBA program that provides the conditional formatting of a large number of cells (which are formatted using the formulas option which refer to cell values in the target spreadsheet). The script and spreadsheet works fine, but I have a problem as immediately after I have run my script (or to be precise a particular input box script has been run) then ghost images appears. (I can easily replicate the issue including on different Windows machines.) The ghost images no longer happen if the user saves the sheet and then re-opens it. However, to me this is not a good solution and makes the program look poor in quality and trustworthiness!
I have a "first" routine that when run (via a button press) uses an Application.Inputbox - this allows the user to select a range of cells. These selection of cells are located in the target worksheet which is a different workbook to where the code is run from. Also, the selection of cells are located in a sheet that is not the front sheet of the workbook concerned.
I then have another second button which when pressed uses collected data and conditionally formats the target spreadsheet. However, after doing this button press I get ghost images appearing (which shows cells from selection made earlier from the first button press).
The screenshot below illustrates the occurrence - you can see that there is a table being shown from the second sheet on the top left-hand side of the sheet (despite not fitting the cells of screen 1!). I hope that makes sense.
Someone kindly below said that I needed to use:
Application.ScreenUpdating=False
and then return it to true at the end.
However, I still have the same ghost images occur and I note these happen after the script has been run.
From researching the topic, I found that this is a common issue from using the property Application.InputBox. If I run my second program without using the first one immediately before it (which has the Application.InputBox) then no ghost images appear. Therefore, I think it is pretty safe to assume the problem has come from this Application.InputBox! However, I have not been able to find a solution! I list below the code used for the first Application.InputBoxs routine.
Sub UserSelectsCells()
Dim rng As Range
Dim wks As Worksheet
Dim wkb As Workbook
If Range("C9") <> False Then
Workbooks.Open Filename:=Range("C9")
End If
On Error Resume Next
Set rng = Application.InputBox( _
Title:="Select Test Cells", _
Prompt:="Please Find The Cells In Your Workbook That Test Whether The User Has Answered The Questions Correctly" & vbCrLf & "Remember this may be in a different sheet in your workbook" & vbCrLf & "These cells must be in a single column", _
Type:=8)
On Error GoTo 0
'Test to ensure User Did not cancel
If rng Is Nothing Then
Workbooks("Version060821.xlsm").Activate
Exit Sub
End If
Workbooks("Version060821.xlsm").Activate
Range("C32").Value = rng.Parent.Parent.Name
Range("C33").Value = rng.Parent.Name
Range("C34").Value = rng.Address
Range("D35").HorizontalAlignment = xlLeft
Range("D35").Value = rng.Count
End sub
Can anyone please find a solution? As an idea, is it possible to somehow clean the memory before my second program is run?
I note that if there is a ghost images problem and I delete all of the conditional formating then the ghost images still appear. I think this is significant because the conditional formatting is linked to the ghost image cells that appear. So, to me this suggests there is some kind of microsoft bug?
I'm not exactly sure why these ghost screens pop up sometimes but I've found that preventing the screen from flashing during your code normally fixes the issue. You can do this by setting Application.ScreenUpdating to False and the beginning of your code. Just be sure to set it back to True at the end! Something like this:
Application.ScreenUpdating = False
[Your code]
Application.ScreenUpdating = True
edit:
After further research, it would appear this is an issue that has been already identified. The workaround below originally comes from here.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim wSheet As Worksheet
On Error Resume Next
Application.ScreenUpdating = False
For Each wSheet In Worksheets
wSheet.Select
Range("A1").Select
Next
Application.ScreenUpdating = True
End Sub
This is definitely a dirty fix but if it works it works. An alternative solution was to scroll up and down using:
Private Sub worksheet_change(ByVal target As Range)
Application.ScreenUpdating = False
ActiveWindow.SmallScroll Down:=-100
ActiveWindow.SmallScroll Up:=100
Application.ScreenUpdating = True
End Sub
Please let me know what works best!
Not enough rep for a comment!
Alec, Workbook_BeforeClose is a workbook event, you don't call it like procedures.
Workbook_BeforeClose Event
From that documentation, "False when the event occurs. If the event procedure sets this argument to True, the close operation stops and the workbook is left open.". So if you add Cancel=True inside it, say, after an if statement check, you can stop the close operation.
Edit: In order to answer the question in comments.
The event is fired when you close the workbook, either from the X in the corner or from the menu, or if you have something like ActiveWorkbook.Close in your code.
You don't have to have a Cancel=True/False inside BeforeClose event's code, depends on if you want to control a premature closure of the workbook. It is required, say, if you were writing the event yourself instead of selecting it in VBA editor. Editor already inserts that parameter.

Is it not a good Idea to use the Set Worksheets method multiple times during code execution?

I am attempting to copy different images to different worksheets of my Workbook using the following code below. I am changing the Target Worksheet Dynamically in a different sub, with a String Variable in the Global Declarations section. I can see the variable being passed to the sub and in fact it works the first pass through the code, but when I attempt to change the "TargetSheetIni" variable to a new sheet, it continues to use the first original sheet as it loops through.
Can you not change a target sheet after using the Set keyword? Should I refer to the sheet directly instead?
Sub Test1()
Dim TargetWS, SourceWS As Worksheet
Set TargetWS = Worksheets(TargetSheetIni)
Set SourceWS = Worksheets("Images")
DoEvents
SourceWS.Shapes(CurrentImageId).Copy
DoEvents
TargetWS.Paste Range(ColumnLetter2 & RwCnter)
DoEvents
End Sub
I think I may have figured it out. As far as I can tell the issue may be that I used the Copy Sheet Functionality in Excel when I originally created the target sheets. And even though I renamed the sheets both on the tab below and in the project editor... for some reason VBA kept targeting only the original sheet
I proved this by changing my code around to explicitly call the sheet I wanted to target like so:
ActiveWorkbook.Worksheets("Sheet2").Paste Range("I2")
And even doing that it would target sheet 1 for the paste command instead of the expected sheet 2. I deleted the three copy sheets and created a new one from scratch and re-executed code and now it targets sheet 2 as expected.
I found this article that sort of explains it I guess...
https://www.spreadsheetsmadeeasy.com/7-common-vba-mistakes-to-avoid/
Ok my last answer may have not been correct. It appears as though for some reason inserting an ws.activate caused my code to start workin.g
Very frustrating fix. as I have always heard to avoid using that.

Range.ClearContents interferes with a paste macro

Hi I have a question about clearing and pasting a selection from another workbook.
I am trying to make a macro that clears the old data I have in a tab and copies the data I have on my clipboard from another excel workbook in it's stead.
I kept getting an error before I noticed what was wrong. When the macro runs the clearing part, it cancels my selection/copy data I had, so the pasting part does not work. does anybody know how to circumvent it? I can't reference the excel where the data is coming from directly because it varies every time.
the code I use now for the clearing:
Sub clearData()
Worksheets("ZRFI08TW").Range("A5:M5000").ClearContents
End Sub
The coded i use now for the pasting of the data (i know its not the best, but trying different things before i noticed the conflict ended up with this one):
Sub copyData()
ActiveSheet.Range("A5").Select
SendKeys "^v"
End Sub
I can come up with two options, following the logic of your code for using SendKeys "^v" for a paste:
Using - Worksheets("ZRFI08TW").Range("A5:M5000") = ""
Assigning the Selection to a range and then selecting this range again and pasting it:
Dim myRange as Range
Set myRange = Selection
Worksheets("ZRFI08TW").Range("A5:M5000").ClearContents
myRange.Select
myRange.Copy
ActiveSheet.Range("A5").Select
SendKeys "^v"
But there should be a way better way to achieve what you are looking for. And as I am mentioning .Select, I feel an urge to mention this one - How to avoid using Select in Excel VBA.

Cutting a region on one worksheet and pasting to another doesn't work. But copy does. Why?

I have been struggling with this problem for awhile now.
I've written a VBA routine that is supposed to find a region on one worksheet, then cut and paste it to another worksheet. If I run the following code it doesn't work:
' This does not work
DSheet.Range(SummaryDataAddr, DSheet.Cells.SpecialCells(xlLastCell)).Cut
PSheet.Range(SummaryDataLocation).PasteSpecial Paste:=xlPasteValues
But if I change the code to copy the region from the first worksheet, paste it to the second worksheet, then go back to the first worksheet and explicitly delete the region, it works.
' But this does work. Why?
DSheet.Range(SummaryDataAddr, DSheet.Cells.SpecialCells(xlLastCell)).Copy
PSheet.Range(SummaryDataLocation).PasteSpecial Paste:=xlPasteValues
DSheet.Range(SummaryDataAddr, DSheet.Cells.SpecialCells(xlLastCell)).Delete
Has anyone seen this kind of problem before? Is there a way to use the cut function and get it all to work?
To access a the spreadsheet with the VBA code in it go here:
https://www.dropbox.com/s/satv6z95tlqw7lr/CutBug.xlsm?dl=0
The routine is called "CreateDLDataPivot" (it's a pared down version of a larger program I'm working on).
Thanks for any help!
PasteSpecial Paste:=xlPasteValues does not work with Range.Cut; it only works with Range.Copy.
Range.Cut only clears the cells, it does not delete the cells.
Try a direct value transfer and clear.
with DSheet.Range(SummaryDataAddr, DSheet.Cells.SpecialCells(xlLastCell))
PSheet.Range(SummaryDataLocation).resize(.rows.count, .columns.count) = .value
.clear 'use .clearcontents to retain formatting
end with

Need to Debug VBA code for Clearing Contents of a Column

I have written a simple macro to clear the contents of column A. My spreadsheet has three sheets called "Input Screen", "Proposal Database", and "Rankings". When I am in the "Proposal database" screen the macro works fine. Howveer, the macro does nto work when it is run from other screens (even though there is nor error with the code). Why is this? Any help will eb much appreciated! The code is as follows:
Sub Clear_Contents_Column_A()
With Worksheets("Proposal Database")
Range("A3", Range("A3").End(xlDown)).ClearContents
End With
End Sub
Thanks,
Ollie
You need to use . before Range. It will specify that Range belongs to certain Worksheet:
Sub Clear_Contents_Column_A()
With Worksheets("Proposal Database")
.Range("A3", .Range("A3").End(xlDown)).ClearContents
End With
End Sub
You're question can be read in different ways. I suspect that #simoco has provided the answer you are looking for, but if you are asking how to use the macro to clear column A in your other worksheets, then you need to change the worksheet name in your macro. You're instructing the macro to run on Sheet ("Proposal Database"). Unless you change the name of the sheet it won't run on other worksheets. You could change
With Worksheets("Proposal Database")
to
With ActiveSheet
if you want the macro to run from any worksheet in the workbook.

Resources