[英]VBA switch statement (or dictionary) to populate a value in an adjacent cell based off first character
I've been trying to piece together several different suggestions to achieve my desired result but I keep coming up with inconsistent results.我一直在尝试拼凑几个不同的建议来达到我想要的结果,但我一直想出不一致的结果。
The workbook I am creating automatically pulls in specific values from other.xls files into column B. In the excel example it pulls in the K221RTA11,K221RTA12, K221RTA13, etc... Column B changes depending on the file imported for use but the common factor is that the values in range B12 through B60 will begin with "L", "B", "Y", "Z", "E", "T", or "A".我正在创建的工作簿自动将 other.xls 文件中的特定值拉入 B 列。在 excel 示例中,它拉入 K221RTA11、K221RTA12、K221RTA13 等。因素是 B12 到 B60 范围内的值将以“L”、“B”、“Y”、“Z”、“E”、“T”或“A”开头。 In the A12-A60 range next to the imported values, I would like for the cells to auto-populate a specific string value based solely on the beginning most letter of the adjacent value in column B.
在导入值旁边的 A12-A60 范围内,我希望单元格仅根据 B 列中相邻值的最开头字母自动填充特定的字符串值。
I've tried using super long nested if statements in the formula bar and it works to an extent but is not scalable for more universal use and is incredibly unwieldy.我已经尝试在公式栏中使用超长嵌套 if 语句,它在一定程度上有效,但不可扩展以供更普遍使用,而且非常笨拙。 I'd like for VBA to listen to the B column assignment and transpose to column A.
我想让 VBA 听 B 列分配并转置到 A 列。
I've updated my code to use VLOOKUP but am not seeing anything populate in the A column.我已更新我的代码以使用 VLOOKUP,但在 A 列中没有看到任何内容。 It's probably that I'm using it incorrectly.
可能是我使用不正确。
Private Sub PopulateTech()
With ThisWorkbook.Worksheets("iNTP")
.Range("B12:B60").Value = WorksheetFunction.Transpose(Array("L", "Z", "B", "D", "F", "E", "T", "A"))
.Range("A12:A60").Value = WorksheetFunction.Transpose(Array("Phone", "Computer", "Keyboard", "Light", "Speaker", "Tablet", "Router", "Switch"))
End With
End Sub
Sub TechVLookup()
Dim tech As String
Set rg = shData.Range("B12:B60")
tech = Left(Application.VLookup("L", rg, 2, False), 1)
Debug.Print tech
End Sub
Option Explicit
Sub TechMatch()
Const lChars As String = "L,Z,B,D,F,E,T,A"
Const lTechs As String _
= "Phone,Computer,Keyboard,Light,Speaker,Tablet,Router,Switch"
Dim Chars() As String: Chars = Split(lChars, ",")
Dim Techs() As String: Techs = Split(lTechs, ",")
Dim Data As Variant
Data = shData.Range("B12:B60").Value
Dim cChar As String
Dim cMatch As Variant
Dim i As Long
For i = 1 To UBound(Data)
cChar = Left(Data(i, 1), 1)
cMatch = Application.Match(cChar, Chars, 0)
If IsNumeric(cMatch) Then
Data(i, 1) = Techs(cMatch - 1) ' - 1 because 0 based.
Else
Data(i, 1) = Empty
End If
Next i
shData.Range("A12:A60").Value = Data
End Sub
Achieved the desired result using formula approach:使用公式方法达到了预期的结果:
=INDEX(Sheet1:B2,$B$11:MATCH(LEFT(B12,$B$60,1):Sheet1,$A$2:$A$11,0)) =INDEX(Sheet1:B2,$B$11:MATCH(左(B12,$B$60,1):Sheet1,$A$2:$A$11,0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.