VBA user defined range and check if it is empty - excel

I have been struggling with this for over an hour. I need to write a VBA code where the user selects a range and then I check if this selected range is empty before I go and do anything else.
This is what I have so far:
Sub test()
Set rng= Application.InputBox("Select the range of the raw data please", Type:=8)
If Application.WorksheetFunction.CountA(Range(rng)) > 0 Then
MsgBox "do this, this and that!"
End If
End Sub
When I run this I get a "Method Range of object_Global failed". I know it lets the user select the range just fine but the Range(rng) is not working right. Any help would be appreciated!

Your problem is that your variable rng is a range and you're trying to wrap that in a range, which is why it's throwing an error. Try this instead.
Sub test()
Dim rng As Range
Set rng = Application.InputBox("Select the range of the raw data please", Type:=8)
If Application.WorksheetFunction.CountA(rng) > 0 Then
MsgBox "do this, this and that!"
End If
End Sub

Just some code
Sub main()
Dim sentRange As Range
Set sentRange = Application.InputBox("Select the range of the raw data please", Type:=8)
If isRangeEmpty(sentRange) = False Then
MsgBox "Range is not empty."
Else
MsgBox "Good to go!"
End If
End Sub
Function isRangeEmpty(ByRef myRange As Range) As Boolean
Dim rngLoop As Range
Dim rangeEmpty As Boolean
For Each rngLoop In myRange
If rngLoop.Value = Empty Then
'All Good
isRangeEmpty = True
Else
'Need to exit
isRangeEmpty = False
Exit For
End If
Next rngLoop
End Function

If you are only acting on the instance of data being present then something like below will work. I would also adding Option Explicit to the top of your code and declare all variables.
Sub How()
Dim rng As Range
Set rng = Application.InputBox("Select Target Range", Type:=8)
If Application.WorksheetFunction.CountA(rng) <> 0 Then
'Actions
End If
End Sub

Related

How can you select a specific range and a pivot table together in VBA?

Good Day,
I am trying to select this range, and well the code seems to process through, but when I get to my if rng is nothing then it does not grab the range. I've been stuck on this for awhile and any thoughts would help. This is also a snippet of the code, but I just assumed this was the most important part.
Note I have to keep this condition, because this section of code will always be called, and if it's empty, it will skip and run the next line. So I cannot just do a select.Again, any thoughts, help would be much appreciated! Ask me any questions if not clear. Thank you so much.
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
On Error Resume Next
Set srng = Sheets("Email Template").PivotTables("PivotTable5")
Set rng = Sheets("Email Template").Range("B3:J13" & srng)
Set DDT = Worksheets("Email Template").Range("X2")
Set Teamail = Worksheets("Email Template").Range("X3")
On Error GoTo 0
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
The first thing you need to do is get the range of the pivot table then if you want to set rng to refer to both B3:J13 and srng use Union.
Dim rng As Range
Dim srng As Range
Dim DDT As Range
Dim Teamail As Range
Dim OutApp As Object
Dim OutMail As Object
Set srng = Sheets("Email Template").PivotTables("PivotTable5").TableRange1
Set rng = Union(Sheets("Email Template").Range("B3:J13"), srng)
Set DDT = Worksheets("Email Template").Range("X2")
Set Teamail = Worksheets("Email Template").Range("X3")
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
End If
P.S. It's not clear which part of the pivot table you want, I've used DataBodyRange but you could use TableRange1 to get the entire table.

How to end the loop is the variable is empty

Sub max()
Sheets(1).Select
Sheets(1).Name = "Sheet1"
Dim rng As Range
Dim celladdress As String
Dim celling As Variant
Do Until IsEmpty(celling)
If celling > "G4" Then
Set rng = Range("G3:G1000").Find(what:="Description")
rng.Find what:="Description"
celladdress = rng.Address(-1)
celling = celladdress
Else: Call Source
End If
Loop
MsgBox "done"
End Sub
Hi im trying to find the word description in my range, if description is foudn then it should run the macro and then loop. but if the variable is empty and the variable description is not found i want the loop to end and display the msgbox. I have tried to end the loop using loop until the celling is empty but it doesnt seem to work. The variable celling is quoting as empty so im unsure why this is not working. Any help would be greatly appreicated thanks max
Max, this is worth posting as a new answer to highlight the unintuitive behaviour of FindNext. This works - better candidate for accepted answer than that above. May be a bit pedantic, as in a more elegant solution is possbile:
Sub max()
Sheets(1).Select
Sheets(1).Name = "Sheet1"
Dim rng As Range
Set rng = Range("G3:G1000")
Dim celladdress As String
Dim celladdressPrevious As String
Dim celling As Range
Set celling = rng.Find(what:="Description")
If celling Is Nothing Then
MsgBox "Not found, exiting"
Exit Sub
End If
Do
'Set celling = range.FindNext 'Keeps returning first range found! Maybe "With" block on rng will work.
If celling.Row > 4 Then
'celling.Activate
celladdress = celling.Offset(-1, 0).Address
If celladdress = celladdressPrevious Then GoTo WereDone
celladdressPrevious = celladdress
MsgBox celladdress
'Else: Call Source 'What is Source? Not this sub, is it?
End If
If celling.Row = 1000 Then Exit Sub
Set rng = Range("G" & celling.Row & ":G1000")
Set celling = rng.Find(what:="Description")
Loop Until celling Is Nothing
WereDone:
MsgBox "done"
End Sub
'Max, guessing a little at your intent - May need your help there. Does this get you closer? I don't think I can do better on a GNU/Linux box.
Sub max()
Sheets(1).Select
Sheets(1).Name = "Sheet1"
Dim rng As Range
Set rng = Range("G3:G1000")
Dim celladdress As String
Dim celling As Range
Set celling = rng.Find(what:="Description")
If celling Is Nothing Then
MsgBox "Not found, exiting"
Exit Sub
End If
Do
'Set celling = range.FindNext 'Keeps returning first range found! Maybe "With" block on rng will work.
If celling.Row > 4 Then
'celling.Activate
celladdress = celling.Offset(-1, 0).Address
MsgBox celladdress
'Else: Call Source 'What is Source? Not this sub, is it?
End If
Set celling = range.FindNext
Loop Until celling Is Nothing
MsgBox "done"
End Sub

Code giving Object Block Variable Error

I have a small userform with one combo box and 2 text boxes and submit button.
While pressing the submit button, i am getting the object variable not set error.
Here is my code:
Private Sub CommandButton1_Click()
Dim ws As Worksheet, tbl As ListObject, row As ListRow
Set ws = Sheets("Create Account Heads")
Set tbl = ws.ListObjects(Me.TextBox2.Value)
Dim intValueToFind As String, rng As Range
Set rng = tbl.ListColumns(1).DataBodyRange
intValueToFind = LCase(Me.TextBox3.Value)
If rng <> 0 Then
For Each rng In rng
If LCase(rng.Value) = intValueToFind Then
MsgBox ("Account Head with this Name Already Exists.")
Exit Sub
End If
Next rng
Else
'Unprotect the Worksheet
ws.Unprotect Password:="google"
End if
End Sub
i am getting the error in "If rng <> 0 Then" line.
Kindly review and advise to overcome this issue.
Thanks
Salman
Replace your line code of:
If rng <> 0 Then
with:
If Not rng Is Nothing Then

Error in copying range using inputboxes from one sheet to anoyher

I have been trying to copy defined range through input-box to defined range through another input-box on other sheet.
I am getting error Run-time error "'1004' Application define or object defined error". on line
rngCopyFrom.Copy ThisWorkbook.Sheets("Sheet2").Range("rngCopyTo")
My level is beginner. Please guide me in what way to change it to serve the desired objective.
Sub Sample()
Dim rngCopyFrom As Range
Dim rngCopyTo As Range
On Error Resume Next
Set rngCopyFrom = Application.InputBox("Enter the range from which you ant to copy", Type:=8)
On Error GoTo 0
On Error Resume Next
Set rngCopyTo = Application.InputBox("Enter the range from which you want to copy", Type:=8)
On Error GoTo 0
If Not rngCopyFrom Is Nothing Then
'~~> Copy the range to Shhet2
rngCopyFrom.Copy ThisWorkbook.Sheets("Sheet2").Range("rngCopyTo")
End If
End Sub
This program works If I define the fixed range as shown in line below.
rngCopyFrom.Copy ThisWorkbook.Sheets("Sheet2").Range("D2:D14")
This should work with 2 input boxes:
Option Explicit
Sub copyRangeFromInputBoxes()
Dim copyFrom As Range, copyTo As Range
Err.Clear
On Error Resume Next 'if input is cancelled
Set copyFrom = Application.InputBox("Select source range", Type:=8)
If Not copyFrom Is Nothing Then 'if not cancelled
Set copyTo = Application.InputBox("Select destination range", Type:=8)
If Not copyTo Is Nothing Then copyFrom.Copy copyTo
End If
End Sub
The code will copy from any sheet and paste on any other sheet:

Define Cell Location Variable in Excel

I'm looking for a way to, instead of typing "ActiveCell.OffSet(1,1) over and over again in my vba code, define that as a variable, "x" and use that instead.
I have to use the dim command to do this but I"m not sure what the data type would be.
Suggestions?
When I test it using the code below I get Runtime Error 1004.
Private Sub CommandButton1_Click()
Dim i As Range
Set i = ActiveCell
ActiveSheet.Range(ActiveSheet.Range(i), ActiveSheet.Range(i).End(xlUp)).Select
End Sub
In response to your edit
Avoid the use of .Select/Activate and fully qualify your objects. INTERESTING READ
Your code can be written as
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim rng1 As Range, rng2 As Range
'~~> Change as applicable
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
Set rng1 = ws.Range("A10")
Set rng2 = .Range(rng1, rng1.End(xlUp))
With rng2
Debug.Print .Address
'
'~~> Do something with the range
'
End With
End With
End Sub
If you still want to know what was wrong with your code then see this.
You have already defined your range. You do not need to add ActiveSheet.Range() again. Your code can be written as
Private Sub CommandButton1_Click()
Dim i As Range
Set i = ActiveCell
ActiveSheet.Range(i, i.End(xlUp)).Select
End Sub
EDIT
Followup from comments
Was ActiveSheet.Range() actually problematic or just redundant? – user3033634 14 mins ago
It is problematic. The default property of a range object is .Value
Consider this example which will explain what went wrong with your code
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
Set rng = .Range("A1")
rng.Value = "Blah"
MsgBox rng '<~~ This will give you "Blah"
MsgBox rng.Value '<~~ This will give you "Blah"
MsgBox rng.Address '<~~ This will give you "$A$1"
MsgBox ws.Range(rng) '<~~ This will give you an error
'~~> Why? Becuase the above is evaluated to
'MsgBox ws.Range("Blah")
MsgBox ws.Range(rng.Address) '<~~ This will give you "Blah"
End With
End Sub
Dim x As Range
Set x = ActiveCell.OffSet(1,1)
EDIT: in response to your comment:
Private Sub CommandButton1_Click()
Dim i As Range
Set i = ActiveCell
ActiveSheet.Range(i, i.End(xlUp)).Select
End Sub

Resources