tags:

views:

287

answers:

3

Hi all,

I'm using vbscript, how do I find the hyphen character "-" in a string and place characters that follow in a new string?

Basically my computer names end with a room number

PC1-3 (room 3) , PC1-4 (room 4) etc

I'm using

Dim roomArray(2)
roomArray = Array("-1", "-2", "-3")

Dim item
For each item in roomArray
 If instr(strComputerName, item)
   ..do something
 End If
Next

but I'm getting false positives due to room -33 containing "-3" etc so if I locate "-" in the string and place the characters that follow into a string I can check against the full string rather than using instr.

Thanks for any help.

A: 

You need to check if strComputerName ends with dash-roomNumber.

if Right(strComputerName,Len(item))=item Then...
yu_sha
A: 

You kan use right and instr to retrieve this

dim s

s = "PC1-3 (room 3)"

msgbox right(s, len(s) - instr(s,"-"))
astander
+1  A: 

This will get all text behind the last hyphen found:

Function GetRoomNumber(strComputerName)
    Dim hyphenIndex

    hyphenIndex = InStrRev(strComputerName, "-")
    If hyphenIndex > 0 Then
      GetRoomNumber = Mid(strComputerName, hyphenIndex+1)
    End If
End Function

Usage in your example will be:

Dim roomArray(2)
roomArray = Array("-1", "-2", "-3")

Dim item, index

For index = LBound(roomArray) To UBound(roomArray)
 item = roomArray(index)
 If ("-" & GetRoomNumber(strComputerName)) = item Then
   ..do something
 End If
Next

Or the short version would be (without defining the function with data validation):

...
If Mid(strComputerName, InStrRev(strComputerName, "-") ) = item Then
...
awe
Hi awe, thanks for your work. I'm having problems as 'item' seems to be empty. Why can't I use MsgBox(item)? It shows an empty message box. ThanksDim itemFor each item in roomArray MsgBox(item)
Jamie
To make sure it is seen as a clean string array you could try this:`Dim roomArray` `roomArray = Split("-1,-2,-3",",")`
awe
You could also try to use index instead of `For Each`: `For index = LBound(roomArray) To UBound(roomArray)` `item = roomArray(index)` ... `Next`
awe