首页 > 解决方案 > 如果函数将两个相同的文本进行比较,不同的值

问题描述

我的两个变量 PackageOptions 和 cell.Value 具有相同的文本但不同的值。是否有一种方法可以格式化它们以匹配以便代码跳转到 if 语句?我尝试使用 Trim$ 和 ascii 格式,但不明白如何格式化。

字符串一是 PackageOptions 类型 字符串二是 PackageOptions 类型

在此处输入图像描述

变量是从列表框中提取的:

Dim PackageOptions
Dim Customer As String
Dim PreferredDate As String
Dim ServicesLine1 As String
Dim PackageOptions As String
Dim GoogleR As Byte
Dim InvoiceR As Byte

For i = 0 To LbCustomer.ListCount - 1
    If LbCustomer.Selected(i) Then
        Customer = Customer & LbCustomer.List(i) & vbNewLine
        PreferredDate = PreferredDate & LbCustomer.List(i, 1) & vbNewLine
        ServicesLine1 = ServicesLine1 & LbCustomer.List(i, 2) & vbNewLine
        **PackageOptions** = PackageOptions & LbCustomer.List(i, 3) & vbNewLine
        GoogleR = GoogleR & LbCustomer.List(i, 4) & vbNewLine  '
        InvoiceR = InvoiceR & LbCustomer.List(i, 5) & vbNewLine  
    End If
Next i

Dim PrRange As Range
Dim cell As RangeSet PrRange = shPrice.Range("PricingTable[Item]")
Dim ItemRange As Range
Set ItemRange = shPrice.Range("PricingTable[Item Number]")

>looping through a table column, return the row and item number of match
>the variables have different values (shown in images attached)
For Each cell In PrRange
         If PackageOptions = cell.Value Then
         ItemR = cell.Row - shPrice.Range("PricingTable[[#Headers],[Item]]").Row
         ItemNumber = shPrice.Range("PricingTable[Item Number]").Cells(ItemR, 1).Value
         End If

Next cell

标签: vbastringif-statement

解决方案


我不太明白你的意思,特别是因为你没有说你在代码的哪一行遇到了哪个错误。也许您的抱怨只是比较没有给出您期望的结果。无论如何,您的变量PackageOptions是 Variant 数据类型变量,其中包含一个字符串,该字符串正是Cell.Value应该包含的,尽管您的支持屏幕将其显示为字符串。

PackageOptions = cell.Value是一个非常粗略但坚固的比较。确保两个项目的数据类型相同。用于Cstr(PackageOptions)将变体强制转换为字符串。也许在两个值上都使用它,Cstr(PackageOptions) = Cstr(cell.Value).

StrComp() 函数允许您有更多的调整空间,但正如其名称所承诺的那样,它比较两个字符串。因此结果不会有任何不同。下面的函数将比较不区分大小写的文本。如果两个字符串相等,它将返回 0(零)。

StrComp(Cstr(PackageOptions), Cstr(cell.Value), VbTextCompare)

推荐阅读