I have a for next loop with an if statement. If the "If statement" is true then exit the if and next for. Here is the code: What I want is if Rng1 is not with in Range1 then goto the next rng1. I seems like a simple solution, but I cannot figure is out. Thank you in advance.
Sub me_test()
Dim Range1 As Range
Dim Rng1 As Range
Set Range1 = Application.Selection
Set Range1 = Application.InputBox("Please Select Your Range :", xtitledID, Range1.Address, Type:=8)
For Each Rng1 In Range1
If Intersect(Rng1, Range("B7:B15")) Is Nothing Then
MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
Else
Rng1.Value = "Good"
End If
Next
MsgBox "All Done"
End Sub
Sub me_test()
Dim Range1 As Range
Dim Rng1 As Range
Set Range1 = Application.Selection
Set Range1 = Application.InputBox("Please Select Your Range :", xtitledID, _
Range1.Address, Type:=8)
Set Range1 = Application.Intersect(Range1, ActiveSheet.Range("B7:B15"))
If Range1 is nothing then
MsgBox "No valid cells selected!"
else
Range1.Value = "Good"
end if
End Sub
This should work. It works on my end
Sub me_test()
Dim Range1 As Range
Dim Rng1 As Range
Dim rngIntr As Range
Set Range1 = Application.Selection
Set Range1 = Application.InputBox("Please Select Your Range :", xtitledID, Range1.Address, Type:=8)
For Each Rng1 In Range1
Set rngIntr = Intersect(Rng1.Cells, Range("B7:B15").Cells)
If rngIntr Is Nothing Then
MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
Else
Rng1.Value = "Good"
End If
Set rngInr = Nothing
Next
Set Range1 = Nothing
Set Rng1 = Nothing
MsgBox "All Done"
End Sub
How about this: Only show the "Not within..." Msgbox if none of the selected cells are within the desired range. Otherwise continue to iterate through the selection and write Good in every cell that is intersecting with the desired range.
Sub me_test2()
Dim Range1 As Range
Dim Rng1 As Range
Set Range1 = Application.Selection
Set Range1 = Application.InputBox("Please Select Your Range :", xtitledID, Range1.Address, Type:=8)
If Intersect(Range("B7:B15"), Range1) Is Nothing Then
MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
Else
For Each Rng1 In Range1
If Not Intersect(Rng1, Range("B7:B15")) Is Nothing Then
Rng1.Value = "Good"
End If
Next
MsgBox "All Done"
End If
End Sub
Maybe:
Sub me_test()
Dim rng1 As Range
Set rng1 = Application.InputBox("Please Select Your Range :", xtitledID, Selection.Address, Type:=8)
If Union(rng1, Range("B7:B15")).Address = Range("B7:B15").Address Then
rng1.Value = "Good"
Else
MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
End If
MsgBox "All Done"
End Sub
You may also want to check for a valid used range selection:
Sub me_test()
Dim rng1 As Range
Do
Set rng1 = Application.InputBox("Please Select Your Range :", xtitledID, Selection.Address, Type:=8)
Loop While rng1 Is Nothing
If Union(rng1, Range("B7:B15")).Address = Range("B7:B15").Address Then
rng1.Value = "Good"
Else
MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
End If
MsgBox "All Done"
End Sub
Related
This VBA takes a lot of time to execute
Sub test()
Dim IB As String
Dim copyRng As Range, cel As Range, pasteRng As Range
With Selection
Set copyRng = Selection
End With
IB = Application.InputBox("Enter Exact Sheet Name to Paste")
Set pasteRng = Sheets(IB).Range("A1")
For Each cel In copyRng
cel.Copy
pasteRng.Range(cel.Address).PasteSpecial xlPasteAll
Next
Application.CutCopyMode = False
End Sub
Copy Non-Contiguous Ranges
I've turned off screen updating and replaced looping through cells with looping through areas of the range.
When you would only need values to be copied, another (vast) improvement in performance would be to copy by assignment. Then in the loop, you would use the following code:
darg.Value = sarg.Value
instead of sarg.Copy darg.
Option Explicit
Sub CopyNonContiguous()
Const ProcTitle As String = "Copy Non-Contiguous"
Dim srg As Range
If TypeName(Selection) = "Range" Then
Set srg = Selection
Else
MsgBox "Select a range. please.", vbCritical, ProcTitle
Exit Sub
End If
Dim wsName As Variant
wsName = Application.InputBox( _
"Enter Sheet Name to Paste", ProcTitle, , , , , , 2)
If wsName = False Then
MsgBox "You canceled.", vbExclamation, ProcTitle
Exit Sub
End If
Dim dws As Worksheet
On Error Resume Next
Set dws = ActiveWorkbook.Worksheets(wsName) ' consider 'ThisWorkbook'
On Error GoTo 0
If dws Is Nothing Then
MsgBox "The worksheet '" & wsName & "' doesn't exist.", _
vbCritical, ProcTitle
Exit Sub
End If
Application.ScreenUpdating = False
Dim sarg As Range
Dim darg As Range
For Each sarg In srg.Areas
Set darg = dws.Range(sarg.Address)
sarg.Copy darg
Next sarg
Application.ScreenUpdating = True
MsgBox "Cells copied.", vbInformation, ProcTitle
End Sub
I have a sheet where there are two columns (Column C and column E). Column E has cells with dropdown menus that are dependent on the value of the cells in the same row, Column C.
I am trying to get the value in Column E to automatically change to the first option of the new corresponding dropdown menu when the value in Column C changes. As it stands, when the value in Column C changes, the value from before in the respective Column E cell remains, and I have to manually click and select from the new list.
Here is what I have to start:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng(1) As Range, rng1 As Range
Set rng(0) = Range("C71:C91")
Set rng(1) = Range("E71:E91")
Application.EnableEvents = False
If Not Intersect(Target, rng(0)) Is Nothing Then
For Each rng1 In rng(1)
i = i + 1
rng1 = Range("" & rng(0).Value2)(i, 1)
Next
End If
Application.EnableEvents = True
End Sub
Haven't fully tested the code, but can see a basic bug. Line:
For Each rng1 In rng(1)
Should read:
For Each rng1 In rng(1).Cells
Recalculate the sheet with Application.CalculateFull after your if statement.
A Worksheet Change with Data Validation (Drop-Downs)
It is assumed that the drop-downs in E71:E91 'get' the values from C71:C91 and that when you change (manually or via VBA) a value in C71:C91, the value in the same row of E71:E91 will be overwritten with this value.
Out-comment or delete the Debug.Print lines when done testing.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Debug.Print "Worksheet Change Sequence at " & Now
Debug.Print "1. '" & Target.Address(0, 0) & "' has changed."
Dim srg As Range: Set srg = Range("C71:C91")
Dim drg As Range: Set drg = Range("E71:E91")
Dim irg As Range: Set irg = Intersect(srg, Target)
Debug.Print "2. Range references created."
If irg Is Nothing Then
Debug.Print "3. No intersecting range. Exiting."
Exit Sub
Else
Debug.Print "3. Intersecting range at '" & irg.Address(0, 0) & "'."
End If
On Error GoTo ClearError
Application.EnableEvents = False
Debug.Print "4. Error handler activated. Events disabled."
' Write to intersecting rows only.
Dim dCol As Long: dCol = drg.Column
Dim iCell As Range
For Each iCell In irg.Cells
iCell.EntireRow.Columns(dCol).Value = iCell.Value
Next iCell
Debug.Print "5. Written to '" _
& Intersect(irg.EntireRow, drg).Address(0, 0) & "'."
'Or:
' Write to whole destination range.
'drg.Value = srg.Value
'Debug.Print "5. Written to '" & drg.Address(0, 0) & "'."
SafeExit:
Application.EnableEvents = True
Debug.Print "6. Events enabled. Exiting."
Exit Sub
ClearError:
Debug.Print "Run-time error '" & Err.Number & "': " & Err.Description
Resume SafeExit
End Sub
' Multi-range example. Best run from 'VBE' with the Immediate window open.
Sub Test()
Range("C71,C73,C75").Value = "A"
Range("C73,C75").Value = "B"
Range("C75").Value = "C"
End Sub
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
I am trying to display all comment text for each worksheet in the Activeworkbook in a MsgBox (for each comment).
My code isn't throwing an error, so I know I am close.
Sub ShowAllWorkbookcomments()
On Error Resume Next
Dim ws As Worksheet
Dim rng As Range
Dim cell As Variant
Dim cmt As String
Dim commentcount As Integer
Set ws = ActiveWorkbook.Worksheets(1)
Set rng = ActiveSheet.Cells.SpecialCells(xlCellTypeComments)
commentcount = rng.Count
'cmt = ws.rng.Comment.Text
Dim varComment As String
Dim c As Comment
For Each ws In ActiveWorkbook.Worksheets
Select Case commentcount
Case 0
MsgBox "No Comment", vbExclamation
Resume Next
Case Is > 0
For Each cell In rng
varComment = c.Text
MsgBox varComment, vbInformation
Next cell
End Select
Set rng = Nothing
Next ws
End Sub
You were close, just needed to get the Set rng = ActiveSheet.Cells.SpecialCells(xlCellTypeComments) inside the For Each ws In ActiveWorkbook.Worksheets loop.
Also, added another way to trap the possibility of a worksheet having no comments, and removed the unnecessary Select Case.
Try the code below:
Option Explicit
Sub ShowAllWorkbookcomments()
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
Dim cmt As String
Dim varComment As String
For Each ws In ActiveWorkbook.Worksheets
On Error Resume Next
Set rng = ws.Cells.SpecialCells(xlCellTypeComments)
On Error GoTo 0
If Not rng Is Nothing Then '<-- current worksheet has comments
For Each cell In rng.Cells
'varComment = cell.Comment.text
varComment = "worksheet " & ws.Name & " comment " & cell.Comment.text ' <-- added the worksheet name as reference
MsgBox varComment, vbInformation
Next cell
Else '<-- current worksheet has No comments >> rng is Nothing
'MsgBox "No Comment", vbExclamation
MsgBox "worksheet " & ws.Name & " has No Comments", vbExclamation ' <-- added the worksheet name as reference
End If
Set rng = Nothing
Next ws
End Sub
As mentioned in one of the comments above, the above logic will cause the MsgBox to be shown for each of the cells in a merged range. The following logic will loop-through the comments in a given sheet, it will work for merged rows/cols scenario as well.
For Each CommentedSheets In ActiveWorkbook.Worksheets
If CommentedSheets.Comments.Count = 0 Then
MsgBox "worksheet " & CommentedSheets.Name & " has No Comments", vbExclamation
Else
For Each Individual_Comment In CommentedSheets.Comments
varComment = "worksheet " & CommentedSheets.Name & " comment " & Individual_Comment.text
MsgBox varComment, vbInformation
I want a VBA code by which I can check every cell in a range with a specific text?
EG: for each cell in range (a:a)
if value of cell = "specific text"
do this
else
do that
*
How to do this in VBA Excel?
here you go, but please try to find on google first
Sub eachCell()
Dim c As Range
For Each c In Range("A1:D21")
If (c.Value = "mytext") Then 'if value of cell = "specific text"
c.Value = "other text" 'do this
Else
c.Value = "other text 2" 'do that
End If
Next c
End Sub
Using a Find loop will be quicker than looking at each cell
Sub Sample_Find()
Dim rng1 As Range
Dim rng2 As Range
Dim bCell As Range
Dim ws As Worksheet
Dim SearchString As String
Dim FoundAt As String
Set ws = Worksheets(1)
Set rng1 = ws.Columns(1)
SearchString = "specific text"
Set rng2 = rng1.Find(SearchString, , xlValues, xlWhole)
If Not rng2 Is Nothing Then
Set bCell = rng2
FoundAt = rng2.Address
MsgBox "do something here " & FoundAt
Do
Set rng2 = rng1.FindNext(After:=rng2)
If Not rng2 Is Nothing Then
If rng2.Address = bCell.Address Then Exit Do
FoundAt = FoundAt & ", " & rng2.Address
MsgBox "do something here " & rng2.Address
Else
Exit Do
End If
Loop
Else
MsgBox SearchString & " not Found"
Exit Sub
End If
MsgBox "The Search String has been found these locations: " & FoundAt
Exit Sub
End Sub
Another option to answer your post, using the AutoFilter.
Code
Option Explicit
Sub Test_AutoFilter()
Dim ws As Worksheet
Dim SearchString As String
Dim Rng As Range
Dim VisRng As Range
Dim c As Range
Set ws = Worksheets(1)
Set Rng = ws.Columns(1)
SearchString = "specific text"
Rng.AutoFilter
Rng.AutoFilter Field:=1, Criteria1:=SearchString
' set another range to only visible cells after the Filter was applied
Set VisRng = ws.Range(Cells(1, 1), Cells(1, 1).End(xlDown)).SpecialCells(xlCellTypeVisible)
If Not VisRng Is Nothing Then
' Option 1: show every cell that a SearchString was found
For Each c In VisRng
MsgBox "String match of " & SearchString & " found as cell " & c.Address
Next c
' Option 2: show all the cells that SearchString was found (in 1 message)
MsgBox "String match of " & SearchString & " found as cells " & VisRng.Address
End If
End Sub