I'm creating an Excel sheet which different people are going to add to, so am wondering if there's any simple way to check for the row where user starts writing being filled?
For example, if user starts typing in cell A1, macro checks if the cells are filled on the same row.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim rsave As Range
Dim cell As Range
Set rsave = Sheet1.Range("a1:i1")
For Each cell In rsave
If cell = "" Then
Dim missdata
missdata = MsgBox("missing data", vbOKOnly, "Missing Data")
Cancel = True
cell.Select
Exit For
End If
Next cell
End Sub
to expand on the suggested solution, you can do the following. Instead of looping through each cell, your problem can be solved efficiently with two lines of code:
'get the used range
Set rsave = Sheet1.Range("a1:i1")
'Select all blank(not yet filled) cells
rsave.SpecialCells(xlCellTypeBlanks).Select
This will select all cells which've not been filled in the range a1:i1 of the sheet. Alternatively, you can use some colour to make it more explicit. If it works, don't forget to accept the answer.
If by saying "data validation", you mean check for blanks, you can use this:
Sub Test()
Dim wrng As Range
Set wrng = ActiveSheet.UsedRange
MsgBox "The data in a range: '" & wrng.Address & "' are" & IIf(IsValidData(wrng), "", "n't") & " valid"
Set wrng = Nothing
End Sub
Function IsValidData(rng As Range) As Boolean
IsValidData = rng.SpecialCells(xlCellTypeBlanks).Count = 0
End Function
Note, that the UsedRange method returns a range starting from A1 cell. So, you need to add extra code to select a range occupied by the data (skip blanks rows and columns).
Sub Test()
Dim wrng As Range
Set wrng = GetDataRange()
MsgBox "The data in a range: '" & wrng.Address & "' are" & IIf(IsValidData(wrng), "", "n't") & " valid"
End Sub
Function GetDataRange() As Range
Dim wrng As Range, c As Range, saddr As String
Dim pos As Integer
'get used range
Set wrng = ActiveSheet.UsedRange
'find first non-empty cell in a used range
saddr = ActiveSheet.Range(wrng.End(xlToLeft).Address, wrng.End(xlUp).Address).Address
pos = InStr(1, saddr, ":")
'skip blanks rows and set new range
Set GetDataRange = ActiveSheet.Range(Mid(saddr, pos + 1, Len(saddr) - pos) & ":" & wrng.SpecialCells(xlCellTypeLastCell).Address)
Set wrng = Nothing
End Function
Good luck!
Related
I have data in Column A in excel..I am iterating through column and i need to find if a cell value has hyperlink init.
LR=Activeworkbook.Worksheets("Emp").Range("A65000").End(xlup).Row
for j=1 to LR
if Thisworkbooks.Worksheets("Emp").cells(j,1)="" then 'Logic to find hyperlink
'Function
end if
next
Identify Cells Containing Hyperlinks
As Red Hare already mentioned in the comments, it is best tested with something like the following:
Dim cell As Range: Set cell = Sheet1.Range("A1")
If cell.Hyperlinks.Count > 0 Then ' has a hyperlink
Else ' has no hyperlink
End If
that is, using the Hyperlinks.Count property of the Hyperlinks object returned by the cell's Hyperlinks property which is a collection of hyperlinks in a range (in this case, a single cell). For a single cell, the Count property will return only 0 or 1 so you could actually use
If cell.Hyperlinks.Count = 1 Then ' has a hyperlink
instead.
Example Code
Option Explicit
Sub IdentifyCellsWithHyperlink()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' If it's not, modify accordingly.
Dim ws As Worksheet: Set ws = wb.Worksheets("Emp")
Dim rg As Range
Set rg = ws.Range("A2", ws.Cells(ws.Rows.Count, "A").End(xlUp))
Dim cell As Range
For Each cell In rg.Cells
If cell.Hyperlinks.Count > 0 Then ' has a hyperlink
Else ' has no hyperlink
End If
Next cell
End Sub
Here is something that can be used to run through each row to determine if it can be set as a hyperlink. Kinda hard to figure out what the range of possible solutions are that will work for you without fully understanding the context...
Private Sub cmdFollowLink_Click()
CreateHyperlink Me!cmdFollowLink, Me!txtSubAddress, _
Me!txtAddress
End Sub
Sub CreateHyperlink(ctlSelected As Control, _
strSubAddress As String, Optional strAddress As String)
Dim hlk As Hyperlink
Select Case ctlSelected.ControlType
Case acLabel, acImage, acCommandButton
Set hlk = ctlSelected.Hyperlink
With hlk
If Not IsMissing(strAddress) Then
.Address = strAddress
Else
.Address = ""
End If
.SubAddress = strSubAddress
.Follow
.Address = ""
.SubAddress = ""
End With
Case Else
MsgBox "The control '" & ctlSelected.Name _
& "' does not support hyperlinks."
End Select
End Sub
I would like to find the cells (or Rows) in Column B, Sheet1, who have matching values placed into ListBox2. Then, I'd like to change the value of a cell 4 columns over (using an Offset command).
I believe using a For loop is the most efficient way of going thru the values placed into ListBox2. I tried using a Forloop to go thru all values placed into ListBox2.List. Upon calling a value, the code would look for this value in Column B. Once found, it would "remember" the Row in which this value was found. Then, the code would use a Range/Offset command to change the value of a cell 4 columns over in that Row.
Private Sub ButtonOK_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim SerialList As Range
Dim SerialRow As Long
Dim i As Long
Set wb = ActiveWorkbook
Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim strFind As Variant
With ws
For i = 0 To Me.ListBox2.ListCount - 1
Set SerialList = ws.Range("B:B").Find(What:=Me.ListBox2.List(i))
SerialRow = SerialList.Row
If Not SerialList Is Nothing Then
ws.Range("B", SerialRow).Offset(0, 4).Value = Me.ListBox2.List(i) 'error occurs here!
MsgBox (ListBox2.List(i) & " found in row: " & SerialList.Row)
Else
MsgBox (ListBox2.List(i) & " not found")
End If
Next i
End With
End Sub
The MsgBoxes do say the correct ListBox2.List(i) value and the correct SerialList.Row, meaning that the program is correctly finding the row in which the list box value is located. However, I get an error saying that my range is not correctly defined at line "ws.Range("B", SerialRow)....."
How do I select the cell I'm searching for to correctly set it to =Me.ListBox2.List(i)?
Couple of fixes:
Dim lv
'....
For i = 0 To Me.ListBox2.ListCount - 1
lv = Me.ListBox2.List(i)
Set SerialList = ws.Range("B:B").Find(What:=lv, LookAt:=xlWhole) '<< be more explicit
'don't try to access SerialList.Row before checking you found a match...
If Not SerialList Is Nothing Then
ws.Cells(SerialList.Row, "F").Value = lv '<< Cells in place of Range
MsgBox (lv & " found in row: " & SerialList.Row)
Else
MsgBox (lv & " not found")
End If
Next i
Sub selecting()
Dim r as Range
Set r = Application.Selection
MsgBox r.Cells(1,1).Address(false,false)
MsgBox r.Cells(1,2).Address(false,false)
MsgBox r.Cells(2,1).Address(false,false)
End Sub
Now the thing is, I select some random cells as irregular range in excel sheet. I get first cell address correct but the next cell address is the cell neighbor to the first one, and not the next cell that I selected.
Basically, I want to collect values from irregular ranges into an array. It would be really helpful if I get addresses of each cell selected in this irregular range.
Simply saying, what I want is if I select cells e1,g4,d7,r1,t3 I should get an array of only these 5 cells in vba program, and this array should have no access to other cells apart from those that were selected.
I am a little unclear on exactly what you are attempting, but I believe this may help you understand the behavior of the script as it's running.
Sub selecting()
Dim myArray(0 To 100, 0 To 1) As Variant
Dim rngSelected As Range
Set rngSelected = Application.Selection
Dim rng As Range
For Each rng In rngSelected
Dim counter As Integer
Debug.Print "The value of cell " & counter & " is " & rng.Value & _
" , and the address is " & rng.Address(False, False)
myArray(counter, 0) = rng.Value
myArray(counter, 1) = rng.Address(False, False)
counter = counter + 1
Next rng
End Sub
Maybe you can tweak this until you get the behavior you are looking for?
I would like to set a range of cells with reference to a named range name1 equal to a similarly sized range of cells on another Excel sheet also referencing a named range name2. I would like the cells in Sheet1 to equal whatever the corresponding cell in Sheet2 currently equals, and therefore I cannot use the .value property.
Sheets("Sheet1").Range("name1").Offset(0, 1).Resize(15, 5) = Sheets("Sheet2").Range("name2").Offset(0, 1).Resize(15, 5).value
Except, that I do not want to use value. Is there a simple way like this to do what I require? I have searched some forums but cannot find a good way to do this. Do I need to use a For each and R1C1 naming? To reiterate - the cells on sheet1 should equal whatever the value is of the relative cell on sheet2 (ranges are the same size). So, eg. cell Sheet1!A1 has the formula =Sheet2!A1.
You could try something like the following:
Sheets("Sheet1").Range("name1").Offset(0, 1).Resize(15, 5).FormulaR1C1 = "=Sheet2!R[0]C[0]"
Update
If the ranges (name1 and name2) are at different positions, you will need to adjust the formula accordingly:
Dim nRowOffset As Long
Dim nColOffset As Long
Dim sFormula As String
nRowOffset = Sheets("Sheet2").Range("name2").Row - Sheets("Sheet1").Range("name1").Row
nColOffset = Sheets("Sheet2").Range("name2").Column - Sheets("Sheet1").Range("name1").Column
sFormula = "=Sheet2!R[" & nRowOffset & "]C[" & nColOffset & "]"
Sheets("Sheet1").Range("name1").Offset(0, 1).Resize(15, 5).FormulaR1C1 = sFormula
I've only tested this a little so it might not be all that robust.
Note This sub needs to be placed in a new (or existing) module, and not in any of the sheet or thisworkbook modules.
It's a macro, and so cannot be called from the worksheet as a UDF. Also, as it has arguments it cannot be directly called.
To use the code you need to create another sub to call this it for you, or call it directly from the immediate window.
Sub RunCode()
Main "Name1", "Name2" ' you could run this line in the immediate/debug window
End Sub
The sub RunCode should be available in the macros menu on in your workbook.
Sub Main(ByVal Name1 As String, ByVal Name2 As String)
Dim Cell As Long
Dim Range1 As Range: Set Range1 = ThisWorkbook.Names(Name1).RefersToRange
Dim Range2 As Range: Set Range2 = ThisWorkbook.Names(Name2).RefersToRange
' check to make sure Name1 and Name2 are the same size
If Range1.Cells.Count = Range2.Cells.Count Then
If Range1.Rows.Count = Range2.Rows.Count Then
If Range1.Columns.Count = Range2.Columns.Count Then
' populate the cells with the formula
For Cell = 1 To Range1.Cells.Count
Range2.Cells(Cell).Formula = "=" & Range1.Worksheet.Name & "!" & Range1.Cells(Cell).Address
Next Cell
End If
End If
End If
End Sub
If you wanted slightly more customizable interface to the function, then the following code should help. Running the RunCode2 macro will prompt you to enter the two names to pass to Main
Public Function nameExists(ByVal Name As String) As Boolean
Dim Result As Boolean: Result = fasle
Dim Item As Variant
For Each Item In ThisWorkbook.Names
If Item.Name = Name Then
Result = True
Exit For
End If
Next Item
nameExists = Result
End Function
Sub RunCode2()
Dim Response As Variant
Dim Name1, Name2 As String
Response = Application.InputBox(Prompt:="Name 1", Type:=2)
If VarType(Response) = vbBoolean Then
Debug.Print "RunCode2 - User Canceled Name 1 Selection"
Exit Sub
Else
If nameExists(Response) = False Then
MsgBox "Name [" & Response & "] Not Found", vbOKOnly
Exit Sub
Else
Name1 = Response
End If
End If
Response = Application.InputBox(Prompt:="Name 2", Type:=2)
If VarType(Response) = vbBoolean Then
Debug.Print "RunCode2 - User Canceled Name 2 Selection"
Exit Sub
Else
If nameExists(Response) = False Then
MsgBox "Name [" & Response & "] Not Found", vbOKOnly
Exit Sub
Else
Name2 = Response
End If
End If
Main Name1, Name2
End Sub
I have a sheet in which I have data from two different sources.I've a blank row between them.I want to make this blank row as my delimiter.How can I find out if the entire row is blank or not.
If you're talking a literal entire row then code similar to this should work (so long as there are no formulas or spaces present in any of the cells as well):
If Application.CountA(ActiveCell.EntireRow)=0 Then
MsgBox "Row Empty"
Exit Sub
End If
Otherwise, for a range from a row:
Dim neValues As Range, neFormulas As Range, MyRange As Range
Set MyRange = Columns("C:AA")
On Error Resume Next
Set neValues = Intersect(ActiveCell.EntireRow.SpecialCells(xlConstants), MyRange)
Set neFormulas = Intersect(ActiveCell.EntireRow.SpecialCells(xlFormulas), MyRange)
On Error GoTo 0
If neValues Is Nothing And neFormulas Is Nothing Then
MsgBox "Nothing There"
Else
MsgBox "Something's There"
End If
(Source: http://www.ozgrid.com/forum/showthread.php?t=26509&page=1)
WorksheetFunction.CountA(), as demonstrated below:
Dim row As Range
Dim sheet As Worksheet
Set sheet = ActiveSheet
For i = 1 To sheet.UsedRange.Rows.Count
Set row = sheet.Rows(i)
If WorksheetFunction.CountA(row) = 0 Then
MsgBox "row " & i & " is empty"
End If
Next i