0

How do I get the length of character between beginning with space and ending with * Here is the image. Column B shows the total len before dasher(-) and my code

enter image description here

Sub xn()
    Dim x As Integer
    x = 1
    If Worksheet("Sheet1").Range("A"& x).len(Right," ") Or _
    Worksheet("Sheet1").Range("A"&x)len(Left,"-") Then
        len(totallen)
    End If
    x = x + 1
End Sub
L42
  • 19,427
  • 11
  • 44
  • 68
lisa_rao007
  • 347
  • 1
  • 5
  • 23
  • You screen shot is not very informative. As for your code, it has many issues. Please post a better screen shot and the actual result you need. – L42 Apr 22 '15 at 01:51

1 Answers1

1

The code posted has multiple issues:

  1. Worksheet is not a valid object - you need to use Worksheets.
  2. .len is not a property of a Range object.
  3. Even in .len was a property of a Range, you would need a de-reference operator (aka '.') in here: Range("A"&x)len(Left,"-")
  4. If you intend to use the function Len(), it only takes one argument.
  5. You apparently are trying to loop, but you need to use either a For or For Each loop - it won't loop automatically when you increment x at the bottom of the sub.
  6. Right is a function, but you're calling it without arguments and they are not optional.
  7. Similarly, Left is a function, but you're also calling it without the required arguments.
  8. totallen is not declared anywhere, so Len(totallen) will assume that totallen is a Variant (default for undeclared variables), then cast it to a String, and then always return 0 because it has never been given a value.
  9. Anything else I may have missed.

The solution is to use the InStr function. It returns the location in a string of a given sub-string.

Sub xn()

    Dim x As Long
    Dim sheet As Worksheet

    Set sheet = ActiveWorkbook.Worksheets("Sheet1")
    For x = 1 To sheet.Range("A" & sheet.Rows.Count).End(xlUp).Row
        sheet.Cells(x, 2) = InStr(1, sheet.Cells(x, 1), "-") - 1
    Next x

End Sub

I'd also recommend taking a look at the MSDN article on Looping Through a Range of Cells (2003 vintage, but still valid), and Error Finding Last Used cell In VBA.

Community
  • 1
  • 1
Comintern
  • 21,855
  • 5
  • 33
  • 80
  • @Comintem thanks working fine but can you explain me second line please what does -1 and are you starting from 0 or 1 i see the dashes but where is the start point – lisa_rao007 Apr 23 '15 at 03:02
  • @user3713336 - InStr is 1 based, so the first parameter is to start from the first character in the cell. It returns the position of what you are searching, so to get a count of characters up to that point you have to subtract 1. For example, `xxxx-xxxx` would return 5 because '-' is the 5th character. – Comintern Apr 23 '15 at 12:06