Simple VBA selection code error - vba

I have this simple VBA code with which I want to change the background of the selected cells. Somehow the command Selection. that I learned before doesn't work. Could you help me with this code? I know the answer is probably stupid, but I can't seem to figure it out.
Sub set_background_color()
'Add background color to selected cells
Selection.Interior.Color = RGB(255, 0, 0)
End Sub
Thanks
EDIT: Sorry for the vague question, it's my first question on stack overflow so I didn't think of the importance of the type of error. It gives me the error "Compile error: Expected function or variable".
It is attached to a button, but even if I run it as a macro without button it gives me the same error.
EDIT 2: I'm running Excel 2011 on a Mac, until now it never gave me any compatibility issues in VBA. However this does not seem to work.

The problem is not within your code, it is within your cells.
Check the locked status of the cells and the protection status of the worksheet.

If your worksheet is not protected then try this
Sub set_background_color()
Dim r As Range
On Error Resume Next
Set r = Selection
On Error GoTo 0
If Not r Is Nothing Then
r.Interior.ColorIndex = 3
Else
MsgBox "Invalid Selection"
End If
End Sub

Related

ppActionRunMacro not working when converted to addin(ppam)

I want to execute a piece of code when the user clicks a rectangle(shape) in the powerpoint slideshow mode . I added a sample code , when the shape names "timelimit" is pressed the script(macro) "correctAns" should be executed. This is working fine when run on the pptm file but when I converted it to ppam file(addin) it is giving the following error
"Runtime error-2147188160 (80048240): ActionSetting(unknown member): Invalid request"
Sub test_action()
With ActivePresentation.Slides(1).Shapes("timelimit").ActionSettings(ppMouseClick)
.Action = ppActionRunMacro
.Run = "correctAns"
End With
End Sub
Sub correctAns()
MsgBox ("correct!!!")
End Sub
I found some similar questions on different forums but couldn't get any solution. Please provide me some suggestions to solve this issue
The PPAM has no slides/shapes, so you'd need to make sure that whatever presentation you're running this in has a shape on slide 1 named "timelimit". Then you'd have the problem of getting the click action to run the macro from within the PPAM.
It'd likely be a lot simpler to add this to your presentation and save it as a PPTM:
Sub correctAns()
Msgbox "correct"
End Sub
Then assign this as the macro to run when the shape is clicked.

Code that works for a form control doesn't work for ActiveX control

First time poster in StackOverflow (but not stackexchange) so please let me know if I can clarify or make any formatting changes. Thank you.
Try as I might, I can't find the answer to this question. I suspect it's due to a lack of understanding when it comes to the basics of VBA. I have knowledge of VBA, but little understanding. That being said, here's the problem.
I've set up a form control Combo Box linked to a macro. I've set the input range to a list of hyperlinks in a different sheet and named the range "Hyperlinks". Each hyperlink is to a different sheet in the workbook. I've set the cell link to a blank sell adjacent to the hyperlinks and named it "Linked_Cell." A picture is below.
Form Control View
The macro code is as follows
Sub DropDown10_Change()
HyperLink_Index = Range("Linked_cell")
If Range("HyperLinks").Offset(HyperLink_Index - 1, 0).Hyperlinks(1).Name <> "" Then
Range("HyperLinks").Offset(HyperLink_Index - 1, 0).Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
End If
End Sub
This automatically moves someone to the sheet they select when they select that sheet from the drop-down menu.
I would like to use an Active X combo box instead of a form control for all the obvious reasons (resize text, etc.) However, I can't get it to work.
I've set "ListFillRange" to "Hyperlinks" and linked cell to "Linked_cell" and entered the same macro code. It looks like this:
View of Active X Combo Box
When I select from the drop down in the Active X Combo box I receive run time error 1004: "Method 'range' of object '_worksheet' failed." I've verified that my named ranges are correct and the code returns no such error when it's in a macro linked to a form control.
Any help is much appreciated! Thank you!
UPDATE: Fixed the Range error by updating the code to the following
Sub ComboBox1_Change()
Dim HyperLink_Index As Range
Set HyperLink_Index = Sheets("SheetList").Range("Linked_Cell")
If Sheets("SheetList").Range("HyperLinks").Offset(HyperLink_Index - 1, 0).Hyperlinks(1).Name <> "" Then
Sheets("SheetList").Range("HyperLinks").Offset(HyperLink_Index - 1, 0).Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
End If
End Sub
I now receive a Type Mismatch error on the beginning of the IF statement. I don't see the error and still have no idea why this behavior doesn't appear for identical macro code linked to a form control.
P.S. Sorry, I don't mean to turn StackOverflow in to my personal debugging team, so the main question I have is "Why is the behavior different between a macro and active x code?"
UPDATE 2: Found a fix. Was using the wrong index. The fix is below. Leaving it here in case someone else can find it useful.
Sub ComboBox1_Change()
If ComboBox1.Value <> "" Then
Sheets("SheetList").Range("Hyperlinks").Hyperlinks(ComboBox1.ListIndex + 1).Follow NewWindow:=False, AddHistory:=True
End If
End Sub
Found a fix. Was using the wrong index. The fix is below. Leaving it here in case someone else can find it useful.
Sub ComboBox1_Change()
If ComboBox1.Value <> "" Then
Sheets("SheetList").Range("Hyperlinks").Hyperlinks(ComboBox1.ListIndex +1).Follow NewWindow:=False, AddHistory:=True
End If
End Sub

Run time error '1004' Unable to get the Match propertyof the WorksheetFunction class

In my macro, I have the following code :
i = Application.WorksheetFunction.Match(str_accrual, Range(Selection, Selection.End(xlToRight)), 0)
where 'str_accrual' is a string captured earlier to this line and the Range selected is in a single row say from "A1" to "BH1" and the result will be a number which is the position of that string in that range selected.
When I run the macro, I get the error:
Run time error '1004' Unable to get the Match propertyof the WorksheetFunction class
But when I run the macro line by line using (F8) key, I don't get this error but when I run the macro continuously I get the error. Again, if the abort the macro and run it again the error doesn't appear.
I tried several times. It seems that if there is no match, the expression will prompt this error
if you want to catch the error, use Application.Match instead
Then you can wrap it with isError
tons of posts on this error but no solution as far as I read the posts. It seems that for various worksheet functions to work, the worksheet must be active/visible. (That's at least my latest finding after my Match() was working randomly for spurious reasons.)
I hoped the mystery was solved, though activating worksheets for this kind of lookup action was a pain and costs a few CPU cycles.
So I played around with syntax variations and it turned out that the code started to work after I removed the underscore line breaks, regardless of the worksheet being displayed. <- well, for some reason I still had to activate the worksheet :-(
'does not work
'Set oCllHeader = ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, _
Application.Match( _
strValue, _
ActiveWorkbook.Worksheets("Auswertung").Range( _
oCllSpielID, _
ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, lastUsedCellInRow(oCllSpielID).Column)), _
0))
'does work (removed the line breaks with underscore for readibility) <- this syntax stopped working later, no way around activating the worksheet :-(
Set oCllHeader = ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, Application.Match(strValue, ActiveWorkbook.Worksheets("Auswertung").Range(oCllSpielID, ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, lastUsedCellInRow(oCllSpielID).Column)), 0))
In the end I am fretting running into more realizations of this mystery and spending lots of time again.
cheers
I was getting this error intermittently. Turns out, it happened when I had a different worksheet active.
As the docs for Range say,
When it's used without an object qualifier (an object to the left of the period), the Range property returns a range on the active sheet.
So, to fix the error you add a qualifier:
Sheet1.Range
I had this issue using a third-party generated xls file that the program was pulling from. When I changed the export from the third-party program to xls (data only) it resolved my issue. So for some of you, maybe there is an issue with pulling data from a cell that isn't just a clean value.
I apologize if my nomenclature isn't great, just a novice to this.
That is what you get if MATCH fails to find the value.
Try this instead:
If Not IsError(Application.Match(str_accrual, Range(Selection, Selection.End(xlToRight)), 0)) Then
i = Application.Match(str_accrual, Range(Selection, Selection.End(xlToRight)), 0)
Else
'do something if no match is found
End If
Update
Here is better code that does not rely on Selection except as a means of user-input for defining the range to be searched.
Sub Test()
Dim str_accrual As String
Dim rngToSearch As Range
str_accrual = InputBox("Search for?")
Set rngToSearch = Range(Selection, Selection.End(xlToRight))
If Not IsError(Application.Match(str_accrual, rngToSearch, 0)) Then
i = Application.Match(str_accrual, rngToSearch, 0)
MsgBox i
Else
MsgBox "no match is found in range(" & rngToSearch.Address & ")."
End If
End Sub
I used "If Not IsError" and the error kept showing. To prevent the error, add the following line as well:
On Local Error Resume Next
when nothing is found, Match returns data type Error, which is different from a number. You may want to try this.
dim result variant
result = Application.Match(....)
if Iserror(result)
then not found
else do your normal thing

VB Error in Excel

I am encountering an error in MS Excel when the following VB code is executed and the "Tracking Changes" feature is turned on:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 1 Then
If IsEmpty(Target) Then
Target.Offset(0, 1).Value = Empty
Else
Target.Offset(0, 5).Value = Now()
End If
End If
End Sub
It seems that I can enter data into the first 2 rows just fine but once I start populating data in the 3rd row and onwards, I get a error stating "run-time error '1004' application-defined or object-defined error".
I get the error from row 2 onwards with this code and track changes turned on. The code however seems to do what it is supposed to do regardless of the error, so I would advise an On Error Resume Next to work around.
This doesn't address any underlying problem with the change tracking and your changes may not be being tracked.
Change Tracking forces the workbook to become Shared, which disables many features (e.g. you can't access VBA with Change Tracking enabled).
I'm not entirely sure why this error is being thrown, but a workaround to avoid seeing this message would be to Resume Next when an error occurs:
On Error Resume Next
Simply add this line of code about your first If block (If Target.Column = 1 Then). Please note that ideally you should want to discern the source of this issue and that this solution is a workaround, which might not be good practice.

Spell check an Excel sheet in VBA

I have scoured the Internet and I have found a handful of possible solutions to this issue, but I wanted to ask here as well.
The goal is to click a button, and spell check an entire sheet.
Here's some code
Sub spellCheck()
Sheet1.Cells.CheckSpelling
End Sub
Also, I found this:
Sub SpellCheck()
Dim Checkword As String, Result As Boolean
Checkword = Selection.Value
Result = Application.CheckSpelling(Checkword)
Selection.Offset(0, 1) = Result
End Sub
Any ideas? Neither is working for me. Thanks!
You can check the whole workbook by doing something like:
Sub SpellCheck()
For Each sh In Worksheets
Sheets(sh.Name).Cells.CheckSpelling
Next
End Sub
this will cycle through each sheet in the entire book and run a spellcheck on each one. What I can't figure out yet is how to make the spell checker actually move to the position of the spelling error. So, with the above you just get a list of spelling errors with no context with which to asses them.
I noticed I just had a typo in my code.
Below works:
Sub spellCheck()
Sheet1.Cells.CheckSpelling
End Sub
But, if anyone knows how to do the entire workbook, I'd be interested in that. Thanks.
This code will work on selected cells .This will highlight if any spell mistakes in a cell
Dim Myrange As Range
Selection.SpecialCells(xlVisible).Select
For Each Myrange In Selection
If Application.CheckSpelling(word:=Myrange.Value) = False Then
Myrange.Font.Color = vbRed
End If
Next
OK, so you can use the following command to invoke the toolbar's spellchecker which does move you to the position of the spelling error as long as you have screen updating enabled at the time.
Application.CommandBars("Tools").Controls("Spelling...").Execute
You can use this command embedded in the loop above to loop through the sheets in the workbook and invoke this command on each new sheet.
Cap
This uses a code snippet from a previous answer to restrict the area used for spellchecking to a specific region. Something I needed to do in a small project. This give the full functionallity of the spellchecker with errors shown in context. The rowNumber is calculated elsewhere.The selection range can be fully controlled elsewhere in your code to suit your particular need. Thought this might help others searching this posting.
With Sheets("Sheet1")
slic = CStr(rowNumber)
.Range("AL3:AN" & slic).Select
Application.CommandBars("Tools").Controls("Spelling...").Execute
End With
Thanks to previous posters this solved a problem form me. I am most grateful.