Hiding Empty Cells - vba

I'm currently working on a code that hides empty cells ,but the problem is i want it to start hiding at a certain range ("A9:A12") not at the beginning of the sheet.
here is my program :
Sub EmptyRow()
'Dim s As String
po = Range("A9:A12").Count
Range("A8").Activate
For i = 1 To po
s = i & ":" & i
If IsEmpty(Cells(i, 1).Value) Then
Rows(s).Select
Selection.EntireRow.Hidden = True
End If
Next
End Sub
The program keeps on hiding cells from the beginning, how do I set it up so it deletes from the range i want it to. Please help.

You can even make your code shorter like this:
For i = 9 To 12
Cells(i, 1).EntireRow.Hidden = IsEmpty(Cells(i, 1).Value)
Next i
Thus, the result of the Hidden property would be dependent on whether the Cells(i,1) is empty. It is easier to understand and to maintain.

Check the solution below. In case you need to change your affected area, just change the value of targetRange.
Sub EmptyRow()
Dim targetRange as Range, po as Long, i as Long
Set targetRange = Range("A9:A12")
po = targetRange.Count
With targetRange
For i = 1 To po
If IsEmpty(.Cells(i, 1).Value) Then
.Rows(i).EntireRow.Hidden = True
End If
Next
End With
End Sub

Sheets("Sheet1").Range("A9:A12").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
SpecialCells results in run-time error if no cells are found, but that can be checked:
If [CountBlank(Sheet1!A9:A12)] Then _
[Sheet1!A9:A12].SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
or ignored:
On Error Resume Next
[Sheet1!A9:A12].SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True

You can get rid of bits like select
Sub EmptyRow()
For i = 9 To 12
If IsEmpty(Cells(i, 1).Value) Then
Cells(i, 1).EntireRow.Hidden = True
End If
Next i
End Sub

Related

VBA Array doesn't work?

I have this practice file with 5 order prices. The goal is to add $20 to each of the record and have a message box to display the result.
Here is the data:
My code is this:
Sub TotalDelivery()
Dim curDelCharge As Currency
Dim curTotal(4)
Dim i As Integer
Worksheets("Sheet1").Range("B10").Activate
Const curDelCharge = 20
For i = 0 To 4
curTotal(i) = ActiveCell.Offset(i, 1).Value + curDelCharge
MsgBox (curTotal(i))
Next i
End Sub
However the message box only displays 20 which is only my curDelCharge value.
To debug, I change the msgbox code into:
MsgBox (ActiveCell.Offset(i, 1).Value)
The return value is blank which means the code doesn't read my ActiveCell value. Why is that?
Thanks in advance!
This line:
curTotal(i) = ActiveCell.Offset(i, 1).Value + curDelCharge
should instead be:
curTotal(i) = ActiveCell.Offset(i, 0).Value + curDelCharge
Putting a "1" will move the offset 1 column to the right, which you don't want.
Sub TotalDelivery()
Dim curTotal(4)
Dim i As Integer
Dim rngCellsToChange As Range 'range of cells you are targeting
Dim rCell As Range 'individual cell in collection of cells. See alternative solution below
'You can refer to cells directly, without activating them.
'You are highly discouraged to use Activate or Select methods.
'Use ThisWorkbook to explicitly tell VBA, which workbook you are targeting
Set rngCellsToChange = ThisWorkbook.Worksheets("Sheet1").Range("B10:B14")
Const curDelCharge = 20
For i = 0 To 4
curTotal(i) = rngCellsToChange(i + 1).Value + curDelCharge
MsgBox (curTotal(i))
Next i
'Alternatively, you can use the Range object to loop through all it's cells, like so:
For Each rCell In rngCellsToChange
MsgBox rCell.Value + curDelCharge
Next
End Sub

Loop counter in checkbox name

I am trying to create a sheet which will have a checkbox in each non-empty line. To automatically adjust the number of checkboxes I created this macro:
Sub checkboxes()
Dim i As Integer
For i = 9 To 200
Set CurCell = ActiveSheet.Cells(i, 3)
If CurCell.Value > 1 Then
ActiveSheet.Shapes("CheckBox" & CStr(i)).Visible = True
Else
ActiveSheet.Shapes("CheckBox" & CStr(i)).Visible = False
End If
Next i
End Sub
I expect number of potential rows with data not greater than 200. Macro checks if value in column C for each line is >1, if true checkbox is visible, else it's hidden.
My problem is that I don't know how to put the loop counter "i" into Shape name - I got an error using code above. Can someone help?
I think this would be a more elegant solution.
This loops through all shapes on ActiveSheet and checks if they are a msoOLEControlObject (see here for more information on that matter).
Sub checkboxes()
Dim curCellValue as Variant
Dim i As Long
For i = 1 To ActiveSheet.Shapes.Count
If ActiveSheet.Shapes(i).Type = msoOLEControlObject Then
curCellValue = ActiveSheet.Cells(i, 3).Value
If curCellValue <> "" Then
ActiveSheet.Shapes(i).Visible = True
Else
ActiveSheet.Shapes(i).Visible = False
End If
End If
Next i
End Sub
So why is this "better"?
You don't have to "guess" how many values there will be.
If you ever change a name of a CheckBox this script will still be working.
This checks for empty cells.
Also note that I replaced Set CurCell = ActiveSheet.Cells(i, 3) with curCellValue = ActiveSheet.Cells(i, 3).Value. You don't need to Set an object in every iteration. Filling the variable suffices.
But: this will check for all msoOLEControlObjects which includes checkboxes, textboxes and the like.
HTH.

Excel VBA - Display next cell if previous cell includes text

I am not a Genius in Excel VBA, so here is my question:
I have an Excel Sheet which has hidden rows.
For example: As long as cell A1 is empty keep the row(A2) hidden. When A1 includes text show the next row (A2).
My Approach was the following:
Sub showRows_Klicken()
Dim rng As Range
For Each rng In Range(Cells(1, 1), Cells(65536, 1).End(xlUp))
If LCase(rng) = "text"
Then
rng.EntireRow.Hidden = False
Else
End If
Next rng
End Sub
I hope somebody can help me out here.
Thanks in advance.
I tried this code. Worked for me. Please give it a try
Sub Macro1()
If Range("A1").Value = vbNullString Then
Columns("B:B").EntireColumn.Hidden = True
ElseIf Not IsEmpty(Range("A1").Value) Then
Columns("B:B").EntireColumn.Hidden = False
End If
End Sub
The Hidden property seems to work. I've changed the function a bit such that it sets the next row (i+1) visible based on row i. It now only checks each 2nd row, otherwise you could hide all rows (if there were nothing), and you would not be able to set any "text" such that the next row is unhidden:
Sub showRows_Klicken()
'loop all rows
For i = 1 To 65536 Step 2
'check if has string "text" and set hidden
If LCase(Cells(i, 1)) = "text" Then
Range(Cells(i + 1, 1), Cells(i + 1, 1)).EntireRow.Hidden = False
Else
Range(Cells(i + 1, 1), Cells(i + 1, 1)).EntireRow.Hidden = True
End If
Next i
End Sub
Thanks for your help, I changed the code a bit and now it works for me:
Sub Schaltfläche259_Klicken()
If Range("A1").Value = vbNullString Then
Rows("2").EntireRow.Hidden = True
ElseIf Not IsEmpty(Range("A1").Value) Then
Rows("2").EntireRow.Hidden = False
End If
End Sub

Excel VBA - How do I refer to a cell's visible content rather than its formula?

I'm trying to loop through a particular range in my Excel spreadsheet(("B13:B65"), to be specific) and hide all rows that have an "X" in them. Something like this:
For i = 13 to 65
If Cells(i, 2) = "x" Or "X" Then Rows(i).RowHeight = 0
Next i
The problem is that I'm getting a type mismatch error.
I assume this is happening because all the cells in this range are formulas rather than text strings. For example, the contents of cell B13 are:
='Monthly'!$C$13
I want my code to evaluate the visible output of the cell, not the actual content.
I get the feeling there's a very easy solution here, but I've been searching for a while with no success. I'm a rookie, obviously...
Based on this example: https://msdn.microsoft.com/en-us/library/office/ff195193.aspx
Sub Main()
For Each c in Worksheets("Sheet1").Range("A1:D10") 'Change for your range
If Lcase(c.Value) = "x" Then
'''Rest of your code
End If
Next c
end sub
You're getting the error because of the OR. There has to be something that can be evaluated to true or false after the Or. Or "X" won't ever be true or false. You need...
If Cells(i, 2) = "x" Or Cells(i, 2) = "X" Then Rows(i).RowHeight = 0
As long as you wanted to use the same code everywhere else.
Use Value property:
If Cells(i, 2).Value = "x"
Loop through static range
Dim rng As Range, c As Range
Set rng = Range("B13:B65")
For Each c In rng.Cells
If UCase(c) = "X" Then
c.EntireRow.Hidden = True
End If
Next c
You could use an AutoFilter
Sub HideEm()
Dim rng1 As Range
Set rng1 = ActiveSheet.Range("$B$1:$B$65")
rng1.Parent.AutoFilterMode = False
rng1.AutoFilter Field:=1, Criteria1:="<>x", Operator:=xlOr, Criteria2:="<>X"
End Sub

Excel VBA Get hyperlink address of specific cell

How do I code Excel VBA to retrieve the url/address of a hyperlink in a specific cell?
I am working on sheet2 of my workbook and it contains about 300 rows. Each rows have a unique hyperlink at column "AD". What I'm trying to go for is to loop on each blank cells in column "J" and change it's value from blank to the hyperlink URL of it's column "AD" cell. I am currently using this code:
do while....
NextToFill = Sheet2.Range("J1").End(xlDown).Offset(1).Address
On Error Resume Next
GetAddress = Sheet2.Range("AD" & Sheet2.Range(NextToFill).Row).Hyperlinks(1).Address
On Error GoTo 0
loop
Problem with the above code is it always get the address of the first hyperlink because the code is .Hyperlinks(1).Address. Is there anyway to get the hyperlink address by range address like maybe sheet1.range("AD32").Hyperlinks.Address?
This should work:
Dim r As Long, h As Hyperlink
For r = 1 To Range("AD1").End(xlDown).Row
For Each h In ActiveSheet.Hyperlinks
If Cells(r, "AD").Address = h.Range.Address Then
Cells(r, "J") = h.Address
End If
Next h
Next r
It's a bit confusing because Range.Address is totally different than Hyperlink.Address (which is your URL), declaring your types will help a lot. This is another case where putting "Option Explicit" at the top of modules would help.
Not sure why we make a big deal, the code is very simple
Sub ExtractURL()
Dim GetURL As String
For i = 3 To 500
If IsEmpty(Cells(i, 1)) = False Then
Sheets("Sheet2").Range("D" & i).Value =
Sheets("Sheet2").Range("A" & i).Hyperlinks(1).Address
End If
Next i
End Sub
My understanding from the comments is that you already have set the column J to a string of the URL. If so this simple script should do the job (It will hyperlink the cell to the address specified inside the cell, You can change the cell text if you wish by changing the textToDisplay option). If i misunderstood this and the string is in column AD simply work out the column number for AD and replace the following line:
fileLink = Cells(i, the number of column AD)
The script:
Sub AddHyperlink()
Dim fileLink As String
Application.ScreenUpdating = False
With ActiveSheet
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = 4 To lastrow
fileLink = Cells(i, 10)
.Hyperlinks.Add Anchor:=Cells(i, 10), _
Address:=fileLink, _
TextToDisplay:=fileLink
Next i
End With
Application.ScreenUpdating = True
End Sub
Try to run for each loop as below:
do while....
NextToFill = Sheet2.Range("J1").End(xlDown).Offset(1).Address
On Error Resume Next
**for each** lnk in Sheet2.Range("AD" & Sheet2.Range(NextToFill).Row).Hyperlinks
GetAddress=lnk.Address
next
On Error GoTo 0
loop
This IMO should be a function to return a string like so.
Public Sub TestHyperLink()
Dim CellRng As Range
Set CellRng = Range("B3")
Dim HyperLinkURLStr As String
HyperLinkURLStr = HyperLinkURLFromCell(CellRng)
Debug.Print HyperLinkURLStr
End Sub
Public Function HyperLinkURLFromCell(CellRng As Range) As String
HyperLinkURLFromCell = CStr(CellRng.Hyperlinks(1).Address)
End Function