VBA案例选择多个条件

use*_*658 5 excel vba excel-vba

VBA新手。我正在尝试构建一个Dimensions值(从excel电子表格中的两个不同单元格中提取,其中一个可能比另一个大,并且我总是想先使用较小的数字)在其中输出(将被串联的字符串)以及来自其他函数的字符串)可能是以下之一:

4868(无x分隔整数值)48x60.5(x分隔整数和实数)36.5x60(x分隔实数和整数)24.75x72.125(x分隔实数和整数)

在VBA中,变量类型被定义为Single(不是Double)。这是我的代码:

Function getDimDisplay(h As Single, w As Single) As String

Dim strResult As String
Dim iH As Integer
Dim iW As Integer
Dim strH As Variant
Dim strW As Variant

iH = CInt(h)
iW = CInt(w)

Select Case h
    Case (h >= w And iH = h And iW = w)
        strH = CStr(iH)
        strW = CStr(iW)
        strResult = strW & strH
    Case (h >= w And iH <> h And iW = w)
        strH = CStr(h)
        strW = CStr(iW)
        strResult = strW & "x" & strH
    Case (w >= h And iH = h And iW <> w)
        strH = CStr(iH)
        strW = CStr(w)
        strResult = strH & "x" & strW
    Case (w >= h And iH <> h And iW <> w)
        strH = CStr(h)
        strW = CStr(w)
        strResult = strH & "x" & strW
End Select

getDimDisplay = strResult

End Function
Run Code Online (Sandbox Code Playgroud)

它将编译,但不会返回任何输出。是什么赋予了?

Mic*_*mes 5

您的变量 'h' 不是布尔值。但是,您在 select case 中调用它以匹配真或假的条件。

将“select case h”更改为“select case true”。一切正常。

Select Case True

Case (h >= w And iH = h And iW = w)
    strH = CStr(iH)
    strW = CStr(iW)
    strResult = strW & strH
Case (h >= w And iH <> h And iW = w)
    strH = CStr(h)
    strW = CStr(iW)
    strResult = strW & "x" & strH
Case (w >= h And iH = h And iW <> w)
    strH = CStr(iH)
    strW = CStr(w)
    strResult = strH & "x" & strW
Case (w >= h And iH <> h And iW <> w)
    strH = CStr(h)
    strW = CStr(w)
    strResult = strH & "x" & strW

End Select
Run Code Online (Sandbox Code Playgroud)


sim*_*rcl 2

选择大小写不是这样工作的。它将呈现的项目 (h) 与针对个别案例陈述计算的值进行比较。

您拥有的 case 语句全部评估为 bool、true 或 fasle。无论 h 等于什么,都不是这样!对于这段代码,您需要一个 if then else if 结构。