基于多变量的 VBA 案例选择
Posted
技术标签:
【中文标题】基于多变量的 VBA 案例选择【英文标题】:VBA Case Select based on Multiple Variables 【发布时间】:2021-03-17 11:14:25 【问题描述】:尝试构建一个 Select Case 语句,该语句执行与嵌套 if 函数类似的工作。本质上,我想根据两列(列 P 和列 I)的值给一个单元格一个值(在列 i + 1 中),然后将它应用到整个数字列到最后一行(因此 lr 变量)
目前,select case
行出现类型不匹配错误。
Dim i As Long
Dim RowNum As Long
Dim lr As Long
Set i = 10
RowNum = 2
lr = Worksheets("1").cells.Find("*", cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row
Set tbl = ActiveSheet.ListObjects("1")
Do Until cells(RowNum, i + 1) = lr
Select Case cells(RowNum, "P") And cells(RowNum, "I").Value
Case Is = "1" And "Available"
cells(RowNum, i + 1).Value = "Purchase"
Case Is = "2" And "Not Available"
cells(RowNum, i + 1).Value = "Attempt Purchase"
Case Is = "3"
cells(RowNum, i + 1).Value = "Purchase Automatic"
Case Is = "4"
cells(RowNum, i + 1).Value = "Do not Purchase"
Case Else
cells(RowNum, i + 1).Value = "N/A"
End Select
RowNum = RowNum + 1
Loop
非常感谢任何帮助。谢谢
【问题讨论】:
您使用了错误的选择案例语法。检查***.com/questions/21319788/…。如果你想要is
语法il.pw.edu.pl/~iap/IAPZ/vbkurs/iso2/rozkazy/select.htm
【参考方案1】:
多选案例
Select Case
需要一种表达方式。用If
声明处理另一个。
片段
Select Case Cells(RowNum, "P")
Case Is = "1"
If Cells(RowNum, "I").Value = "Available" Then
Cells(RowNum, i + 1).Value = "Purchase"
End If
Case Is = "2"
If Cells(RowNum, "I").Value = "Not Available" Then
Cells(RowNum, i + 1).Value = "Attempt Purchase"
End If
Case Is = "3"
Cells(RowNum, i + 1).Value = "Purchase Automatic"
Case Is = "4"
Cells(RowNum, i + 1).Value = "Do not Purchase"
Case Else
Cells(RowNum, i + 1).Value = "N/A"
End Select
【讨论】:
【参考方案2】:如果您阅读过 Select Case 结构的工作原理,您会意识到您构建 Select Case 的方式是不可能的。在 VBA IDE 中,将光标放在 Select 上并按 F1。这将打开 Select Case 的帮助页面。
要实现类似于您需要实现的目标,您需要连接两个值以给出一个值并相应地调整大小写值。下面的代码假定“CStr(Cells(RowNum, "I").Value" 等价于 "" 以使 Case 结构中的 Case 标签正常工作。
您还应该知道“Set i”是不正确的,因为 I 是值变量而不是引用变量。使用 i=10。
Dim i As Long
Dim RowNum As Long
Dim lr As Long
i = 10
RowNum = 2
lr = Worksheets("1").Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row
Set tbl = ActiveSheet.ListObjects("1")
Do Until Cells(RowNum, i + 1) = lr
Select Case Trim$(CStr(Cells(RowNum, "P").Value) & CStr(Cells(RowNum, "I").Value))
Case "1Available"
Cells(RowNum, i + 1).Value = "Purchase"
Case Is = "2Not Available"
Cells(RowNum, i + 1).Value = "Attempt Purchase"
Case Is = "3"
Cells(RowNum, i + 1).Value = "Purchase Automatic"
Case Is = "4"
Cells(RowNum, i + 1).Value = "Do not Purchase"
Case Else
Cells(RowNum, i + 1).Value = "N/A"
End Select
RowNum = RowNum + 1
Loop
【讨论】:
以上是关于基于多变量的 VBA 案例选择的主要内容,如果未能解决你的问题,请参考以下文章