VBA function value problem

hc002

New Member
Joined
Apr 10, 2014
Messages
5
The following formula is resulting in "0" in cell H2. The actual result should be 13 which can be determined when place the =LEN(D2) function in the H2 cell. Ultimately I want to run a macro which will count the length of the cell in all hows of the D column and past the result in the H column which didn't work so I created this short test. Can someone tell me the problem with this? Thanks

Sub CountSpaces()
Dim nn As Integer
nn = Len(D2)
Range("H2").Value = nn
End Sub
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
Code:
Sub countSpaces()
    For x = 1 To Cells(Rows.Count, "D").End(xlUp).Row
        Cells(x, 8).Value = Len(Cells(x, 4))
    Next x
End Sub
 
Upvote 0
Code:
Sub CountSpaces()
Range("H2").Value = Len(Range("D2").Value)
End Sub


The reason yours didn't work is because D2 is seen as an object and you haven't set the value.

Code:
Sub CountSpaces2()
Dim nn As Integer
Dim D2 As String
D2 = "123"
nn = Len(D2)
Range("H2").Value = nn
End Sub
 
Upvote 0
Here's it is checking the length of the variable D2, which presumably doesn't exist and is therefore zero. You can avoid this btw, by putting OPTION EXPLICIT at the top of your code.

Notwithstanding, you need to reference the range explicitly
Code:
nn = Len(Sheets("Sheet1").Range("D2").Value)

Hope that helps.


/AJ
 
Upvote 0

Forum statistics

Threads
1,215,052
Messages
6,122,878
Members
449,097
Latest member
dbomb1414

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top