Hiding a column that appears within an entered range - excel

In my data sheet, I want to allow users to hide whichever columns they want, but column F cannot be hidden. When the user wants to hide a column, they push a button which brings up an input form, and they can enter the column(s) they want to hide. I have it working if column F is specifically mentioned(i.e. user inputs "F" or "A,C,F,G" etc), but I'm not sure how to go about if they enter it as a range and F isn't specified (i.e. A-G, E-I, etc.). Here's the code that I have:
If Len(TheColumn) <= 2 Then
If Hide = True And TheColumn = "F" Then
MsgBox "Sorry, you cannot hide column F", vbOKOnly, "Action cancelled!"
Exit Sub
End If
Else
If InStr(1, TheColumn, ",F,") > 0 Or InStr(1, TheColumn, ",F") > 0 Or Left(TheColumn, 1) = "F" Then
MsgBox "Sorry, you cannot hide column F", vbOKOnly, "Action cancelled!"
Exit Sub
End If
End If
I thought about using ASC to find out if ASC("F") is between the ASC of the first and last letters, but it only counts the first character, so ASC("AA") is the same as ASC("A"), which could cause issues if you want to hide "Z-AB"
Also just realized my code below won't work if they enter a range that doesn't encompass F (i.e A-D) anyway.
sStart = 1
Do Until sStart > Len(TheColumn)
sEnd = InStr(sStart, TheColumn, ",") - 1
If sEnd = -1 Then sEnd = Len(TheColumn)
col = Mid(TheColumn, sStart, sEnd - sStart + 1)
If Show = True Then
Range(col & "1").EntireColumn.Hidden = False
Else
Range(col & "1").EntireColumn.Hidden = True
End If
sStart = sEnd + 2
Loop

You can use regular expression to make it usable for Range to hide columns in one line instead of using loops. At the end of code you just make sure that column F is always visible.
Sub F()
Dim cols, re
Set re = CreateObject("VBScript.RegExp")
re.Global = True: re.Pattern = "([A-Z]{1,2})(?=,|$)"
cols = "A,C,E,F": cols = re.Replace(cols, "$1:$1") '=> A:A,C:C,E:E,F:F
Range(cols).EntireColumn.Hidden = True
Columns("F").Hidden = False
End Sub

Related

Search for a match across two columns in same row VBA

I have a simple program below that allows a user to input a vehicle with its hours and expenses for a specific date. The data is recorded on a sheet called "Data". I want to ensure that there is no repeated data entered for the same vehicle type for the same date as that would be redundant data. I was using the excel "find" function to achieve similar results in other places in my program but was having difficulty doing the same here as I now need to ensure that two columns in the same row have matching text. For reference, here is how I checked for matches in other parts of the code:
SDes = ""
a = 0
On Error GoTo continue
SDes = Sheets("Vehicles").Range("Dyn_Vehicles").Find(txtName)
Search = Me.txtName.Text
Set foundcell = Worksheets("Vehicles").Columns(1).Find(Search, LookAt:=xlWhole, LookIn:=xlValues)
'if exists - return record row
If Not foundcell Is Nothing Then RecordRow = foundcell.Row
If SDes <> "" Then
a = a + 1
Else
continue:
SDes = "0"
a = 0
End If
If a >= 1 Then
answer = MsgBox("Data already exists. Would you like to overwrite the previous entry?", vbCritical + vbYesNo, "Data Exists")
If answer = vbYes Then
Sheets("Vehicles").Range("Data_Start1").Offset(RecordRow - 1, 0) = expUF.txtName
Sheets("Vehicles").Range("Data_Start1").Offset(RecordRow - 1, 1) = expUF.txtRp
Sheets("Vehicles").Range("Data_Start1").Offset(RecordRow - 1, 2) = expUF.txtOC
MsgBox "Previous entry overwritten.", vbInformation, "Entry Overwritten"
Exit Sub
Else
MsgBox "New entry was not added.", vbInformation, "Entry Not Added"
Exit Sub
End If
End If
If a = 0 Then
MsgBox ("New vehicle added."), vbInformation, "Vehicle Added"
End If
Sheets("Vehicles").Range("Data_Start1").Offset(TargetRow, 0) = expUF.txtName
Sheets("Vehicles").Range("Data_Start1").Offset(TargetRow, 1) = expUF.txtRp
Sheets("Vehicles").Range("Data_Start1").Offset(TargetRow, 2) = expUF.txtOC
End If
userform
excel data
If you are just trying to remove duplicate data consider this. This will search the sheet, and range for any data that matches on the first two columns and remove duplicates. You can extend the array range if you want to encompass more than your Name and Date field as your "comparing" fields.
Sub test()
Worksheets("Vehicles").Range("Dyn_Vehicles").RemoveDuplicates Columns:=Array(1, 2)
End Sub

Inserting Blank Rows in Excel VBA

Hey I have been writing some code to add a part ID to a spreadsheet off of a user form in Excel VBA. I have been reading through different documentation and can not figure out why no matter what type of method of inserting a row I try it inserts a row with a repeating value instead of a blank one. If anyone knows how to specify blank, other than writing the whole row to blank and then writing my numbers I want after, that would be appreciated.
I have tried both the following lines to add a row
Cells (x+1 ,column).EntireRow.Insert Shift:= xlDown
ws1.Rows(x+1).Insert Shift:=xlDown
This is the function it is used in:
Public Sub Add(IDRange As Range)
SearchCell = Cells(x, IDRange.Column)
Cells(x, IDRange.Column).Select
Do
If SearchCell = PartID Then
MsgBox " this Company Already uses this part"
Exit Sub
ElseIf x <> StopRow Then
x = x + 1
SearchCell = Cells(x, IDRange.Column)
End If
Loop While x <> StopRow And SearchCell <> PartID
Cells(x + 1, IDRange.Column).EntireRow.Insert Shift:=xlDown
Cells(x, IDRange.Column).Value = PartID
MsgBox PartID & " has been added to Adress " & Cells(x, IDRange.Column).Address
Cells(x, IDRange.Column).Select
End Sub
Bellow is the function that calls the Add Function and where I belive it may be getting the company name from
Private Sub AddPart_Click()
AddPartCounter = 0
Company = UserForm1.CompanyBox.Value
PartID = UserForm1.PartBox.Value
If Company = "" Then
MsgBox " Please put in the company you would like the part to go under"
ElseIf PartID = "" Then
MsgBox " Please put in the Part you would like entered"
ElseIf UserForm1.Studs.Value = False And UserForm1.Spreaders.Value = False And UserForm1.Blocks.Value = False And UserForm1.Imma.Value = False Then
MsgBox "Please select the type of part you are trying to add"
Else
Dim CurrentCell
Set CurrentCell = Cells.Find(What:=Company, LookAt:=xlWhole)
If CurrentCell Is Nothing Then
MsgBox " Company Not Found "
Exit Sub
End If
x = CurrentCell.Row
Do
Set CurrentCell = CurrentCell.Offset(1, 0)
Loop While CurrentCell.Offset(1, 0) = "" And Not CurrentCell Is Nothing And CurrentCell.Offset(1, 0).Row <> thisvar.Row + 1
StopRow = CurrentCell.Row
'If they are trying to add a nut
If UserForm1.Imma.Value = True Then
Call Add(Nut_ID_Rng)
'IF they are trying to add a stud
ElseIf UserForm1.Studs.Value = True Then
Call Add(Stud_ID_Rng)
'If they are trying to add a block
ElseIf UserForm1.Blocks.Value = True Then
Call Add(Block_ID_Rng)
'If they are trying to add a spreader
ElseIf UserForm1.Spreaders.Value = True Then
Call Add(Spreader_ID_Rng)
End If
End If
AddPartCounter = 1
End Sub
I know that the repeating pattern is coming from the insert line through debugging but I can not figure out why I have tried changing variables to numbers and it still did the same thing. This what it looks like with the repeating values.
enter image description here
The problem is that you most likely have a value still stored in your clipboard when you execute the Macro. To fix that, simply add this line of dode before running the insert line:
Applcation.CutCopyMode = False
That will clear your clipboard and allow the inserted rows to be blank.

Hiding all rows below cells containing certain text

I am looking to hide all rows (until row 150), that contain a certain text in a certain column. The column contains a drop down of two choices, "Yes" and "No". If the answer is yes, I want to hide all the rows below, if it is no, then not hide.
ie, C2 is "No", don't hide. C3 is "Yes", hide...There are 150 rows of Yes or no, but once yes, you can hide all the rows.
I've tried to cycle the code below and it works with the first cell, but all rows after that do not work
Option Explicit
Private Sub HideRows(ByVal Target As Range)
If Range("C2").Value = "Yes - provide details" Then
Rows("3:150").EntireRow.Hidden = True
ElseIf Range("C2").Value = "No" Then
Rows("3:150").EntireRow.Hidden = False
End If
If Range("C3").Value = "Yes - provide details" Then
Rows("4:150").EntireRow.Hidden = True
ElseIf Range("C3").Value = "No" Then
Rows("4:150").EntireRow.Hidden = False
End If
' all the way through to C149
If Range("C149").Value = "Yes - provide details" Then
Rows("150").EntireRow.Hidden = True
ElseIf Range("C149").Value = "No" Then
Rows("150").EntireRow.Hidden = False
End If
End Sub
I expected to be able to cycle through the first If code, but it doesn't work after the 1st set of them
(this is untested)
Rows("3:150").EntireRow.Hidden = False
For i = 2 to 150
If Range("C" & i).Value = "Yes - provide details" Then
Rows(i + 1 & ":150").EntireRow.Hidden = True
Exit For
End If
Next i
Since it looks like you don’t want to filter because you want all rows below a “yes” to be hidden. I would recommend doing a loop.
Option Explicit
Sub HideRows()
Dim currRow as Integer: currRow = 1
Dim continue as Boolean: continue = True
While continue
If cells(currRow,3) = "Yes - provide details" then
rows(currRow & ":150").EntireRow.Hidden = true
continue = False
Else
currRow = currRow + 1
End If
Wend
End Sub
This is untested from mobile.

ActiveX Command Button that unhides next to a Cell if a value is entered, and hides if the cell is empty

I have 80 rows where the user can enter a predetermined value under column Ward. This unhides a button next to it. Upon clicking it, it empties the adjacent value and increments (+1) a particular cell in another sheet depending on the original value.
Currently, I have 80 ActiveX buttons next to the Ward cells that hides/unhides depending on the value of the Ward cells. I've noticed that adding more buttons slows down the spreadsheet because of the sheer volume of If Then statements I have.
If Range("F8").Value = 0 Then
Sheets("Admissions").EDAdmit1.Visible = False
Else
Sheets("Admissions").EDAdmit1.Visible = True
End If
If Range("L8").Value = 0 Then
Sheets("Admissions").ElecAdmit1.Visible = False
Else
Sheets("Admissions").ElecAdmit1.Visible = True
End If
If Range("F9").Value = 0 Then
Sheets("Admissions").EDAdmit2.Visible = False
Else
Sheets("Admissions").EDAdmit2.Visible = True
End If
If Range("L9").Value = 0 Then
Sheets("Admissions").ElecAdmit2.Visible = False
Else
Sheets("Admissions").ElecAdmit2.Visible = True
End If
.. and so on.
Not to mention the If Then statements I have for every button click.
Private Sub EDAdmit1_Click()
If Range("F8") = "ICU" Then
Worksheets("Overview").Range("AD11").Value = Worksheets("Overview").Range("AD11") + 1
ElseIf Range("F8") = "HDU" Then
Worksheets("Overview").Range("AF11").Value = Worksheets("Overview").Range("AF11") + 1
ElseIf Range("F8") = "DPU" Or Range("F8") = "Other" Then
Else
Col = WorksheetFunction.VLookup(Range("F8"), Range("U1:V27"), 2)
Worksheets("Overview").Range(Col).Value = Worksheets("Overview").Range(Col).Value + 1
End If
Range("F8").ClearContents
End Sub
Is there a more efficient way of doing this?
Admission List:
You could consider using "admit" hyperlinks in the cells next to the Ward selections: that way you only need one handler (Worksheet_FollowHyperlink in the worksheet module). Note you need to use Insert >> Hyperlink and not the HYPERLINK() formula-type links here (because formula-based links don't trigger the FollowHyperlink event).
You can ditch the hide/show code and instead use conditional formatting to change the link font color to hide the links when there's no Ward selected. If a user clicks on one of the hidden links then you can just do nothing.
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim rngSrc As Range, addr, ward
Set rngSrc = Target.Range '<< the cell with the link
ward = rngSrc.Offset(0, 1).Value '<< cell with Ward
'only do anything if a ward is selected
If Len(ward) > 0 Then
'find the cell to update
Select Case ward
Case "ICU"
addr = "AD11"
Case "HDU"
addr = "AF11"
Case "DPU", "Other"
addr = ""
Case Else
addr = Application.VLookup(ward, Me.Range("U1:V27"), 2, False)
End Select
'if we have a cell to update then
If Len(addr) > 0 Then
With Worksheets("Overview").Range(addr)
.Value = .Value + 1
End With
End If
rngSrc.Offset(0, 1).ClearContents
End If
rngSrc.Select '<< select the clicked-on link cell
' (in case the link points elsewhere)
End Sub
At the beginning of your code put this line:
Application.ScreenUpdating = False
this will disable all screen updates. Let your code do changes, and then enable screen updating, and all your changes will appear.
Application.ScreenUpdating = True
Disabling screen updating usually makes the execution of code faster.

How can I look for the duplicate values in a certain field in a spreadsheet?

I have an Excel file and want to look for the duplicate values in a certain field like a list of email accounts. Like making them to be formatted the same or something like that.
How to do that?
When using Excel version 2007, built functionality can be used to remove duplication.
The command is on tab Data, a group Data Tools;
icon Remove duplicates.
Or use a macro. To mark duplicated values by the tag, such as X to an adjacent column.
Next, they can be used by auto filter, to filter out the rows marked and by keyboard shortcuts
CTRL + - (minus key) duplicates can be removed at once.
Option Explicit
'crea by pc-prog.eu
Sub SelectRowOfDupli_A()
Dim x As Variant, xRng As Range, xR As Range
Dim xMltRow As String, i As Integer, xObl As String
Set xRng = Selection
x = "xxxxxx"
On Error GoTo xErr
xObl = "B"
xObl = InputBox("Enter COLUMN where by 'X' sign will be marked duplicate entries " & _
"of selected cells:", "RANGE", xObl)
If xObl = "" Then
MsgBox "Column name must be entered!", vbCritical, "CHYBA"
Else
For Each xR In xRng
If Trim(CStr(xR.Value)) = x Then
Range(xObl & CStr(xR.Row)).Value = "X"
i = i + 1
Else
x = Trim(CStr(xR.Value)) 'xR.Value
End If
Next xR
If xMltRow <> "" Then
Range(xMltRow).Select
End If
MsgBox "Done. " & CStr(i) & " duplicates."
End If
Exit Sub
xErr:
MsgBox Err.Description, vbCritical, "FINISHED WITH ERRORS:"
End Sub
You can find duplicates in a column by using making another column containing the formula (assuming you're checking column Q) COUNTIF(Q:Q, Q2).
You can then use conditional formatting to highlight rows where the new column's value is > 1.

Resources