VBA set cell value after .ClearContents - vba

Why does the cell value not set in another function when clearing the contents of the range in another function?
I'm trying to set a cell value to "All" after clearing the cells in the range. I've even tried to get a message box to pop up to see if i can somehow check if my check value is correct.
DelRange is the range i'm clearing.
Building is the cell that i'm checking the value for and if it's blank, it needs to change to "All".
clearPreviw is used to clear another sheet, which it's doing.
Sub ClearSheet()
Dim Dash As Worksheet
Dim DelRange As Range
Dim Building As Range
Set Dash = ActiveWorkbook.Worksheets("DASH")
Set DelRange = Dash.Range("FilterData")
Set Building = Dash.Range("SelBuild")
DelRange.ClearContents
Call clearPreview
'This part below doesn't work when the Range.ClearContents has been done, but doing it on it's own without clearing the range works fine
If Building.Value = "" Then
MsgBox "Building is empty", vbOKOnly
Building.Value = "All"
End If
End Sub
I've run this test as a separate process which works, but once again when running it as a call function right after .ClearContents seems to stop this.
Sub test()
Dim Dash As Worksheet
Dim DelRange As Range
Dim Building As Range
Set Dash = ActiveWorkbook.Worksheets("DASH")
Set DelRange = Dash.Range("FilterData")
Set Building = Dash.Range("SelBuild")
If Building.Value = "" Then
MsgBox "Building is empty", vbOKOnly
Building.Value = "All"
End If
End Sub
I've been poking at it and searching but i can't wrap my head around this.

I think you are missing:
Building.ClearContents;
Also I would prefer:
If IsEmpty(Building.Value) Then
over:
If Building.Value = "" Then

This link gives you a good start on how to set range variables (although I would advice you against the use of .Select and .Activate).
After that, use .ClearContents or .Clear, depending on your needs.
If you properly cleared the ranges, there is no need to check if they are empty, so this might be a redundant step within your current planning.

Related

Ignore blanks in a range

Can some one help with the last bit of this code please, I have a range maximum ("A1:A54") when i set to this range and only (A1:A10) have a cell value which is the name of a sheet in another workbook.
This code is working but returns a
runtime 9 error
I really want to add if blank ignore if I change to range I have set to A1:A10 then no error. I think it might be there is no worksheets in the other workbook this is why I get an error on this loop.
Have looked how to ignore blanks but none of the answers i have found have worked.
I really want a if cell = "" then ignore currently I thought exit sub would work
Sub Iedextraction()
Dim wkb As Excel.Workbook, wkb1 As Excel.Workbook
Dim wks As Excel.Worksheet, wks1 As Excel.Worksheet
Dim cell As Range
Dim rng As Range
Workbooks.Open Filename:= _
"D:\Projects\ASE Templates\ASE Template White Book.xlsx"
Set wkb = Excel.Workbooks("ASE RTU Addressing with Automation.xlsm")
Set wks = wkb.Worksheets("Tab Names from White book")
Set wkb1 = Excel.Workbooks("ASE Template White Book.xlsx")
Set rng = wks.Range("A1:A54")
For Each cell In rng
wkb1.Sheets(cell.Value).Copy After:=Workbooks_
("ASE RTU Addressing with Automation.xlsm").Sheets(4)
If cell = "" Then Exit Sub
Next
' On Error GoTo 0
End Sub
Add conditional instruction:
If cl <> "" Then wkb1.Sheets(cell.Value).Copy After:=Workbooks _
("ASE RTU Addressing with Automation.xlsm").Sheets(4)
And remove:
If cell = "" Then Exit Sub
Your error occurs most probably because you try to copy before you do the check. So, at the end, you try to get a sheet with no name. :)
It is better practice to use dynamic ranges since it's likely going to change at some point in the future. There are multiple ways of doing this, but my go to method is something like this:
Dim rn As Range
Set rn = Range(Range("A1"), Range("A1").End(xlDown))
So your issue would be resolved (assuming the blank cells are truly empty) and you will not have to test for blank cells.
Regardless, you should mark one of the above answers are correct if they fixed your issue.

Application or Object defined error in range.formula

I am trying to set a formula to certain cells. The code for setting the formula in a for loop is like this:
For i = 0 To MotorAmount
Set myCell = Range(Target.Address).Offset(i, 1)
myCell.Formula = "=IFERROR(VLOOKUP(Range(Target.Address);Database!$B$31:$G$131;2;False);0)"
Next i
However I get an application or object defined error on the line that starts with myCell.Formula. I hope someone can tell me why the error occurs and how to fix it.
PS: I use semicolons in the formula because my Excel works like that. the 'Database' is the name of another sheet I use.
PS2: The sub is placed in Sheet1 under Microsoft Excel Objects in the VBAProject.
The complete code is:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim myRange As Range
Dim myCell As Range
Dim i As Integer
Dim MotorAmount As Integer
Set myRange = Range("A68:A168")
If Not Application.Intersect(myRange, Range(Target.Address)) Is Nothing Then
If Not Range(Target.Address) = "" Then
MotorAmount = InputBox("How many motors are used in this transport?", "Amount of motors")
For i = 0 To MotorAmount
Set myCell = Range(Target.Address).Offset(i, 1)
myCell.Formula = "=IFERROR(VLOOKUP(Range(Target.Address);Database!$B$31:$G$131;2;False);0)"
Next i
End If
End If
End Sub
Your formula implementation should be:
myCell.Formula = "=IFERROR(VLOOKUP(" & Target.Address & ",Database!$B$31:$G$131,2,False),0)"
Note: In VBA use commas while writing formula, in native it will automatically show the correct argument separator you are using.
You can't put code inside a formula and you should be using commas not semicolons in the formula as VBA is US-centric. I'd suggest using R1C1 references:
myCell.FormulaR1C1 = "=IFERROR(VLOOKUP(R" & Target.Row & "C1,Database!R31C2:R131C7,2,False),0)"

Excel VBA code to select all cells with data sometimes working

I once built a VBA button to automatically lock all cells with data in them. And it was working perfectly. Now I wanted to copy that button to another worksheet. So I created another button, copy and pasted the whole VBA over, then edited the worksheet names and range. And, it's only working like 5% of the time, the rest of the time, I'm getting an "Run-Time error '1004': No cells were found." I've tried a few fixed, changing Sheets to Worksheets, or adding a ", 23" to the specialcells argument. However, nothing is working right now. When I try stepping in, it sometimes say both rng and lckrng as empty, and sometimes only show lockrng as empty and not show rng at all. Problem is this used to be a working code, and now, it still works around 5% of time. Any idea why? Thank you very much!
Private Sub CommandButton1_Click()
Dim rng As Range
Dim lockrng As Range
Sheets("Uploading Checklist (M)").Unprotect Password:="signature"
Set rng = Range("A1:M14")
'Selecting hardcoded data and formulas
Set lockrng = Union(rng.SpecialCells(xlCellTypeConstants), rng.SpecialCells(xlCellTypeFormulas))
lockrng.Locked = True
Sheets("Uploading Checklist (M)").Protect Password:="signature"
End Sub
Maybe this is too simplistic, but it seems to do what you want. The animated .gif shows it working to "lock all cells with data in them". (I made the second button just for convenience). If nothing else it might be good to start from something like this that works and modify to suit your needs.
Dim cell As Range, sh As Worksheet
Sub Button4_Click()
Set sh = Worksheets("Sheet1")
sh.Unprotect Password:="s"
For Each cell In sh.UsedRange
If cell <> "" Then cell.Locked = True Else cell.Locked = False
Next
sh.Protect Password:="s"
End Sub
Sub Button5_Click()
Set sh = Worksheets("Sheet1")
sh.Unprotect Password:="s"
End Sub
The Union you are attempting will not work if either of the parameters is Nothing (i.e. you either have no constants in the range, or you have no formulas in the range).
Prior to doing the Union, you should check the parameters aren't Nothing but, once you start changing your code to do that, it would be just as simple to do the locking in two parts - so I recommend you rewrite the code as follows:
Private Sub CommandButton1_Click()
With Sheets("Uploading Checklist (M)")
.Unprotect Password:="signature"
With .Range("A1:M14")
'Lock any constants
If Not .SpecialCells(xlCellTypeConstants) Is Nothing Then
.SpecialCells(xlCellTypeConstants).Locked = True
End If
'Lock any formulas
If Not .SpecialCells(xlCellTypeFormulas) Is Nothing Then
.SpecialCells(xlCellTypeFormulas).Locked = True
End If
End With
.Protect Password:="signature"
End With
End Sub

Populating ComboBox with dynamic values from another worksheet

---Update---
Thanks for the responses, I have found that DragonSamu's updated answer works perfectly.
---Original Post---
I have been trying to figure out where I am going wrong for the past few hours but I can't spot it. I think it's because the script is trying to draw the value from the active worksheet which is not what I want. Hopefully somebody can put me on the rite track - I think the answer should be relatively obvious but I just can't see it!
Basically, I am trying to populate a Combobox with a dynamic range of values that exist in another worksheet (but in the same workbook). I can get the Combobox to populate when I run the script in the worksheet 'Materials' (which is where the dynamic list is drawn from) but not when I run it in the worksheet 'Products'.
Unfortunately the script is designed to populate Products with Materials so is be run in a UserForm when the 'Products' worksheet is open and the 'Materials' worksheet would therefore be inactive.
I should also note that this script has been adapted from code I found elsewhere on this forum, so if it seems familiar I thank you in advance :)
Private Sub UserForm_Initialize()
Dim rRange As Range
On Error GoTo ErrorHandle
'We set our range = the cell B7 in Materials
Set rRange = Worksheets("Materials").Range("B7")
'Check if the cell is empty
If Len(rRange.Formula) = 0 Then
MsgBox "The list is empty"
GoTo BeforeExit
End If
'Finds the next empty row and expands rRange
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = Range(rRange, rRange.End(xlDown))
End If
'The range's address is our rowsource
Mat1_Name_ComBox.RowSource = rRange.Address
Mat2_Name_ComBox.RowSource = rRange.Address
Mat3_Name_ComBox.RowSource = rRange.Address
Mat4_Name_ComBox.RowSource = rRange.Address
Mat5_Name_ComBox.RowSource = rRange.Address
BeforeExit:
Set rRange = Nothing
Exit Sub
ErrorHandle:
MsgBox Err.Description
Resume BeforeExit
End Sub
Any help is much appreciated.
Cheers,
Simon
From what I can see your code would be giving an error here:
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = Range(rRange, rRange.End(xlDown))
End If
Because your trying to set rRange by using Range() without defining the Worksheet first. This will get the Range from the ActiveWorksheet.
change it to the following:
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = Worksheets("Materials").Range(rRange, rRange.End(xlDown))
End If
best practice would be the following:
Private Sub UserForm_Initialize()
Dim wb as Workbook
Dim sh as Worksheet
Dim rRange As Range
On Error GoTo ErrorHandle
'Set the Workbook and Worksheet
set wb = Workbooks("products.xlsx")
set sh = wb.Worksheets("Materials")
'We set our range = the cell B7 in Materials
Set rRange = sh.Range("B7")
'Check if the cell is empty
If Len(rRange.Formula) = 0 Then
MsgBox "The list is empty"
GoTo BeforeExit
End If
'Finds the next empty row and expands rRange
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = sh.Range(rRange, rRange.End(xlDown))
End If
By properly defining and setting your Workbook and Worksheet you correctly reference to them and don't get errors.
Update:
the 2nd problem is that rRange.Address only places the Range location inside your .RowSource not the Sheet it needs to look at.
change:
Mat1_Name_ComBox.RowSource = rRange.Address
to:
dim strSheet as String
strSheet = "Materials"
Mat1_Name_ComBox.RowSource = strSheet + "!" + rRange.Address
This way it will include the Sheet name into the .RowSource

Trying to loops through multiple cells in VBA

I've searched online and found a few solutions, but none of them make sense to me. I'm wondering why this specifically doesn't work:
Dim rng As Range: Set rng = Range("A5:A10")
For Each cell In rng
Dim contents As String: contents = ThisWorkbook.Sheets("ROI's").Range("cell").Value
MsgBox (contents)
Next cell
(BTW this is within a larger macro which works)
It keep saying that the error is on the third line
In addition to Scott Craners answer, take the parenthesis away from around contents in MsgBox (contents), you are not placing it into a variable so it should not be enclosed.
Sub try2()
Dim rng As Range
Dim cell As Range
Dim contents As String
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
Set rng = Range("A1:A10")
For Each cell In rng
contents = ws.Range(cell.Address(0, 0)).Value
MsgBox (contents)
Next cell
End Sub
I've been practicing wtih various problems concerning VBA...the above is just a snippet synthesizing what all the fine people above me have said about making this work. My 2 cents, brackets or not around the contents variable, the result is the same.