VBA identify column header of highlighted cells - vba

I'm new to VBA. I'm using an excel sheet with dropdowns selected by a user in cells A10:E10. My macro runs data validation on the information inputted by the user. If data entered does not fit parameters set by the macro, the cell is highlighted. At the end of the macro I would like a MsgBox stating that highlighted cells exist in x column/s. Here is what I have:
Sub CheckErrors()
Range("A11:E100000").Select
Dim high As Range
Dim c As Range
Set high = Selection
For Each c In high
If c.Interior.Pattern <> xlNone Then
MsgBox ("Please update highlighted cells in " & c.Column & " and run Data Validation again")
Exit Sub
End If
Next c
MsgBox ("Data verification is complete")
End Sub
Instead of saying c.Column I would ideally like the code to identify which cells are highlighted and display the column header in A10:E10. For instance, if B24 and C82 are highlighted I would like the MsgBox to state "Please update highlighted cells found in Phone Numbers and Addresses". "Phone Numbers" and "Addresses" would be the values in cells B10 and C10 respectively and would come from a dropdown list that the user previously selected.
Any help would be much appreciated. Thanks!

Easy! You've already done most of the work by getting the column, all you need to do is insert your value with the appropriate row and you've got it. Here is what your message box line should look like:
`MsgBox ("Please update hilighted cells in " & Cells(10, c.Column).value & " and run Data Validation again")`
I'm not sure how familiar you are with cells, but it is Cells(row index, column index) and using the .Value property returns the contents of that cell. Assuming that your headers are in the 10th row of your workbook, this should get you what you are looking for.

Related

Hyperlink not working correctly [duplicate]

This question already has an answer here:
Macro to Hyperlink a cell to itself
(1 answer)
Closed 4 years ago.
I have two hyperlinks in my excel document.
On Sheet1, in cell A1 I have written the formula, =HYPERLINK("#'Sheet1'!A1","click").
On Sheet1, in cell A2 I have done what I think is the same but using a interactive GUI. Right click in cell A2 => Hyperlink => Place in this document => (Type the cell reference) A2.
I also have written a very short sub so that when I click on these hyperlinks I get a message box.
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
MsgBox ActiveCell
End Sub
I have placed this macro in Sheet1.
When I click on cell A2 I get a MsgBox with the cell value in. As expected
However, when I click on cell A1 nothing happens.
Why are these two links behaving differently? How can I make cell A1 behave in the same way as cell A2 whilst still using a formula in the cell?
So Why?
I have a program that generates a CSV file. For simplicity the structure looks a little like this.
f1,f2,compare
f3,f2,compare
This means it is easy to overwrite the format.
I then open this file and save it as a .xlsm. What I wanted to have is when the compare is clicked it would run a macro. This could be in the form of a button or a hyperlink or anything else as long as it is obviously clickable.
Hence why I was going for the approach of =HYPERLINK("#'Sheet1'!A1","click") as it was easy to increment the number after the column and still show it was something that was clearly clickable.
Therefore it would be a quick change to get the CSV file output in a format of
f1,f2,"=HYPERLINK(""#'Sheet1'!C1"",""compare"")"
f3,f2,"=HYPERLINK(""#'Sheet1'!C2"",""compare"")"
The goal of this is to have something that is as automated as possible as this workbook could have over a thousand row so it is not feasible for me to manually sort out a compare button on each row
Update 2
When the compare button is clicked, a macro is run. This macro is called CompareFiles. It takes the values from the cells on the same row but in columns a and b, passes them into a shell command, and opens a different program that is used to compare the files.
What you can do is select all the cells that need linking to themselves and use a answer by Gary's Student to do it. The original post can be found here
Sub HyperAdder()
Dim r As Range, s As String
For Each r In Selection
If Len(r.Text) = 0 Then
s = "X"
Else
s = r.Text
End If
ActiveSheet.Hyperlinks.Add Anchor:=r, Address:="", SubAddress:=r.Parent.Name & "!" & r.Address(0, 0), TextToDisplay:=s
Next r
End Sub
If you are using a .vbs file like myself, in my case to convert the .csv and do a few other things, then you can use something similar to the following.
For Each cell In YourSheet.UsedRange.Columns("C:F").Cells
If Len(cell.Text) > 0 Then
ConflictsSheet.Hyperlinks.Add cell, "", "'" & cell.Parent.Name & "'" & "!" & cell.Address(0, 0), cell.Text
End If
Next

Lookup in all the sheets for specific text and if match then write value of same row but different column value to master sheet

check over all sheets
If specific text (e.g., yes) is found in the fifth row of a sheet, get data from that row (but different column) and write data to a master sheet
How can I do that?
I found below code relatively useful for me but, not 100% matching with my requirement. please help me on this.
Problem in this code is:- i have specific text(yes) in specific range(e6:e16).
What I want is to check for only yes word. If found then write value of column A & row, in which yes word found, into master sheet and check it till last sheet.
Sub SeachSheets()
Dim FirstAddress As String, WhatFor As String
Dim Cell As Range, Sheet As Worksheet
WhatFor = InputBox("What are you looking for?", "Search Criteria")
If WhatFor = Empty Then Exit Sub
For Each Sheet In Sheets
If Sheet.Name <> "SEARCH" Then
With Sheet.Columns(1)
Set Cell = .Find(WhatFor, LookIn:=xlValues, LookAt:=xlPart)
If Not Cell Is Nothing Then
FirstAddress = Cell.Address
Do
Cell.EntireRow.Copy _
Destination:=Sheets("SEARCH").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
Set Cell = .FindNext(Cell)
Loop Until Cell Is Nothing Or Cell.Address = FirstAddress
End If
End With
End If
Next Sheet
Set Cell = Nothing
End Sub
Any help will be appreciated.
Thank you.
For one sheet, this is easy to accomplish with a formula alone, e.g.
= INDEX(1:1,MATCH("yes",5:5,0))
This finds the first instance of yes in the 5th row of the current sheet, and returns the value in 1st row and in the same column.
One option is to have this formula above somewhere on each sheet in your workbook as a "helper cell" (e.g. cell Z99) and then have a formula somewhere on your master sheet to check all of these helper cells, e.g.
= IFERROR(Sheet1!Z99,IFERROR(Sheet2!Z99,IFERROR(Sheet3!Z99,IFERROR(...,"no match"))))
Of course, also possible without helper cells at all, but the formula just gets messy:
= IFERROR(INDEX(Sheet1!1:1,MATCH("yes",Sheet1!5:5,0)),
IFERROR(INDEX(Sheet2!1:1,MATCH("yes",Sheet2!5:5,0)),
IFERROR(INDEX(Sheet3!1:1,MATCH("yes",Sheet3!5:5,0)),
IFERROR(...,"no match"))))
If you want a way without explicitly calling each sheet, then VBA is probably required. Just posting a solution without VBA to see if this will work for you.

My VBA macro is working but I need it to paste as values

I am very new to VBA and macros.
I have used a macro to copy from one sheet and paste into another in the next available column. This is great and exactly what I want but I need it to paste as values. I have tried what everyone has said but still having no luck.
What changes do I need to make?
Sub HistoricalData()
Dim TargetSht As Worksheet, SourceSht As Worksheet, SourceCol As Integer, SourceCells As Range
'If an error occurs skip code to the Err-Hanlder line and the display the error message.
On Error GoTo Err_Handler
'This is the sheet where your copy information from. Change "Sheet1" to the name of your soure sheet
Set SourceSht = ThisWorkbook.Sheets("BARGE LIVE TRACKING")
'Name of the sheet where data is to be copied to. Rename Sheet2 to the name of your target sheet
Set TargetSht = ThisWorkbook.Sheets("Sheet9")
'This is the cells you will copy data from. This is targeting cells B1 to the last used cell in column B
Set SourceCells = SourceSht.Range("I3:I" & SourceSht.Range("I65536").End(xlUp).Row)
'This is finding the next column available in the target sheet. It assumes dates will be in row 1 and data in row 2 down
If TargetSht.Range("A1").Value = "" Then
'Cell A1 is blank so the column to put data in will be column #1 (ie A)
SourceCol = 1
ElseIf TargetSht.Range("IV1").Value <> "" Then
'Cell IV1 has something in it so we have reached the maximum number of columns we can use in this sheet.
'Dont paste the data but advise'
MsgBox "There are no more columns available in the sheet " & TargetSht.Name, vbCritical, "No More Data Can Be Copied"
'stop the macro at this point
Exit Sub
Else
'cell A1 does have data and we havent reached the last column yet so find the next available column
SourceCol = TargetSht.Range("IV1").End(xlToLeft).Column + 1
End If
'Put in the date in the appropriate column in row 1 of the target sheet
TargetSht.Cells(1, SourceCol).Value = Format(Date, "DD/MM/YYYY")
'We can now start copying data. This will copy the cells in column B from the source sheet to row 2+ in the target sheet
SourceCells.Copy TargetSht.Cells(2, SourceCol)
'Advise the user that the process was successful
MsgBox "Data copied successfully!", vbInformation, "Process Complete"
Exit Sub 'This is to stop the procedure so we dont display the error message every time.
Err_Handler:
MsgBox "The following error occured:" & vbLf & "Error #: " & Err.Number & vbLf & "Description: " & Err.Description, _
vbCritical, "An Error Has Occured", Err.HelpFile, Err.HelpContext
End Sub
As a general rule you can always record your steps with "record macro". This is an excellent way to help you learn the ins and outs of VBA.
If you don't see the developer tab on your excel ribbon you can learn how to show it HERE.
On the developer tab click record macro. It will ask you to name the macro but will give it a name Macro1, which is fine. While recording, highlight the formula cells that you want to copy values from and copy (cntrl-C or right-click - Copy).
Then pick another cell to begin the paste. Right click on that cell and choose "Paste Special." Then choose "Values" and only the values will be pasted. Then go click Stop Recording.
Then go to your VBA editor and look for the macro in a module. You'll find that user3598756's answer is correct. This is a very easy way to teach yourself basic functions of excel.

VBA to create formula causes 1004 error when parentheses entered and causes an update values box when space is entered

I have a UserForm with TextBoxes that are used in creating new sheets from a template.
The gist of how this all works is that the VBA creates a copy of a "template sheet" that is hidden in the workbook. It names this copy based on the values entered by the user in the form's TextBox.
Additionally, I have a Summary sheet that is, as the name implies, a summary of different information entered in the sheet(s) the user has created.
To relieve the need for users to manually copy info into the Summary sheet, I'm using a formula tied to a function which will update the Summary sheet for them.
Now, when the user finishes entering their information into the UserForm, they click a Generate Workbook button which runs the code below which build formulas into the Summary sheet based on the info entered in the UserForm TextBox.
I have two issues when the VBA attempts to add a formula to the cells in the Summary Sheet.
Issue 1:
When a space is entered into the TextBox, it opens a "Update Values" dialog box when the user clicks the Generate Workbook button.
Example - Project 1234
Issue 2:
When parentheses are entered into the TextBox, a 1004 error occurs when the user clicks the Generate Workbook button.
Example - Project1234(Mobile)
If no parentheses and no spaces are entered, it all works fine.
There are 25 possible entries in the UserForm.
Each entry has three TextBoxes: ProjectNameTXT, SheetNameTXT, and ProjectNumTXT - each numbered 1-25 (i.e., ProjectNameTXT1, SheetNameTXT1, ProjectNumTXT1).
The two issues only pertain to the SheetNameTXT TextBoxes.
The csvRange is the function I mentioned earlier.
Here's the relevant code.
Code in UserForm1:
Private Sub GenerateWorkbook_Click()
Dim ws As Worksheet
Dim k As Long
Dim strSName
For k = 1 To 25
strSName = Me.Controls("SheetNameTXT" & k).Text
'Creates a data sheet for each project.
'Uses the MASTER SHEET as a template.
Set ws = ThisWorkbook.Worksheets("MASTER SHEET")
ws.Copy ThisWorkbook.Sheets(Sheets.count)
ActiveSheet.Name = strSName
ActiveSheet.Visible = xlSheetHidden
ThisWorkbook.Worksheets("Summary").Select
'THIS IS THE CODE CAUSING THE ISSUES
Range("B" & k + 3).Value = "=IF(ISERROR(csvRange(" & strSName & "!A2:A2500)),"""",csvRange(" & strSName & "!A2:A2500))"
Next k
Unload UserForm1
End Sub
Code for the Function csvRange:
Function csvRange(myRange As Range)
Dim csvRangeOutput
For Each entry In myRange
If Not IsEmpty(entry.Value) Then
'Create comma separated value
csvRangeOutput = csvRangeOutput & entry.Value & ", "
End If
Next
'Removes the last comma and space.
csvRange = Left(csvRangeOutput, Len(csvRangeOutput) - 2)
End Function
The csvRange function is a modified version of this function that muncherelli created:
https://superuser.com/a/241233
I'm not the world's greatest VBA coder, so apologies if my syntax or methodology sucks. Feel free to improve and provide suggestions if you are so inclined.
I searched StackOverflow and didn't find anything that would solve the problem. Tried some of the solutions suggested for similar problems but no luck getting them to fix these issues.
As always, your help and constructive criticism are much appreciated.
Put single quotes around your sheet name in your formula.
"=IF(ISERROR(csvRange('" & strSName & "'!A2:A2500)),"""",csvRange('" & strSName & "'!A2:A2500))

VBA Vlookup formula, value does not appear in cell

My problem is that when i put this code in VBA:
Sub formula_vlookup()
'MONTHS
ActiveSheet.Cells(ActiveCell.Row, 1).Select
ActiveCell.Offset(0, 16).Select
With ActiveCell
.formula = "=IF(ISNA(VLOOKUP(" & .Offset(0, -16).Address(0, 1) & ",'CZ support'!$A:$AA,2,0)), _
"""",(VLOOKUP(" & .Offset(0, -16).Address(0, 1) & ",'CZ support'!$A:$AA,2,0)))"
End With
End Sub
It works perfectly ( i mean , it gives me the value of the cell that is "vlooked up" but the problem is that it does not display that value in the cell, so the only way to know if its a value there is making a SUM of the cells that contain this formula.
how can i manage this problem?
Thank you in advance for your help
Things to check:
Name [CZ Support] (with a BLANK in the middle) may be invalid ... I can't create that in XLS2010
check that the name exists (Name manager or just try to select it from the drop down left of formula bar)
Try entering the same formula (with .Offset(...) expanded to actual cell addresses) directly in worksheet cell(s)
Try replacing the "" in the FALSE part of the =IF(...) by some text (e.g. "not found") to see if you're caught by an exception
Try replacing the last VLOOKUP argument (0) by TRUE or FALSE as per the documentation
Try assigning the formula to a string variable first and examine it in the debugger window (or do a Debug.Print thereof)
pasting your code "as is" gave me an error - my VBA doesn't like the line splitting underscore in the formula generation