我想根据单元格的值将字符串设置为某个字母。单元格应该只有值," P1"," P2"," P3"," P4"。如果细胞是" P1"然后我想设置字符串" products2" as" a&#34 ;,如果" 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
答案 0 :(得分:2)
这是一个可以执行您想要的版本,并将其扩展到P3等。我必须将wash
设置为某个位置才能使代码生效。它假定您访问的单元格中的值的格式为Pi
,其中i
是整数。它获得i
的值,向下移动1,然后获得将字母表中的字母移动i
(所以" a"对于0," b&# 34; 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
答案 1 :(得分:1)
它现在的存在方式,它试图将products
与变量而不是字符串进行比较
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
阅读时扫描更容易。
答案 2 :(得分:0)
我的尝试
Function StrOut(strIn As String)
StrOut = Chr(96 + CLng(Replace(strIn, "P", vbNullString)))
End Function
测试
Sub TestDaCode()
Debug.Print StrOut("P1")
Debug.Print StrOut("P2")
End Sub