Excel Vba获取单元格的值并设置一个string
我想根据单元格的值设置一个string作为特定的字母。 单元格应该只有值“P1”,“P2”,“P3”,“P4”。 如果单元格是“P1”,那么我想将string“products2”设置为“a”,如果其“P2”我要将“products2”设置为“b”…
这里是代码,它将获得单元格的正确值,但不会使用它来设置products2。
Dim Products As String Dim Products2 As String Products = wash.offset(1, 3).Value If Products = P1 Then Products2 = "a" ElseIf Products = P2 Then MsgBox "we got here" Products2 = "b" End If MsgBox "products2 = " & Products2
这是一个可以做你想做的事情的版本,然后把它扩展到P3等等。我不得不把它wash
到某个位置来让代码工作。 它假定你正在访问的单元格中的值是Pi
的forms,其中i
是一个整数。 它得到i
的价值,向下移动1,然后得到字母移到i
的字母(所以“a”为0,“b”为1等)
Sub ProdString() Dim Products As String Dim Products2 As String Dim i As Long Dim wash as Range Set wash = Range("A1") Products = wash.Offset(1, 3).Value Products = Mid(Trim(Products), 2) 'strip off the "P" i = Val(Trim(Products)) - 1 Products2 = Chr(i + Asc("a")) MsgBox "Products2 = " & Products2 End Sub
它现在存在的方式是试图将products
与variables而不是string进行比较
Dim Products As String Dim Products2 As String Products = cstr(trim(wash.offset(1, 3).Value)) If Products = "P1" Then Products2 = "a" ElseIf Products = "P2" Then MsgBox "we got here" Products2 = "b" End If MsgBox "products2 = " & Products2
一个很好的方法来扩展它,所以它很容易覆盖“P1”到“P4”将是使用select
语句如下:
Products = CStr(Trim(wash.Offset(1, 3).value)) Select Case Products Case "P1": Products2 = "a" Case "P2": Products2 = "b" Case "P3": Products2 = "c" Case "P4": Products2 = "d" End Select MsgBox "products2 = " & Products2
阅读时扫描要容易得多。
我的企图
Function StrOut(strIn As String) StrOut = Chr(96 + CLng(Replace(strIn, "P", vbNullString))) End Function
testing
Sub TestDaCode() Debug.Print StrOut("P1") Debug.Print StrOut("P2") End Sub