在VBA中声明变量来分析字符串(但偏移以查看数字!)

时间:2015-07-10 12:49:52

标签: excel vba excel-vba

在下面的代码中,我声明了要使用的c,但它似乎只适用于数字。我正在寻找一个字符串来与同一张表上另一个表中的另一个字符串进行比较。

使这个棘手的问题是我想将值偏移到左边的单元格,然后将一个日期与另一个日期进行比较。为了更清楚,我的数据格式如下:(称之为SetA)

         A        B         C         D    E  F      G          H          I
CreateTime  LotID  AnalysisSet  Slot#  X  Y  ResultType  TermName  ResultName

右边的几列......让我们称之为SetB

     Y        Z        AA       AB    AC  AD     AE          AF        AG
CreateTime  LotID  AnalysisSet  Slot#  X  Y  ResultType  TermName  ResultName

以下是代码:

Sub AIM36DBOCompare()
Dim n As Integer
n = 2
Dim PasteCount As Integer
Dim test1 As Long
Dim test2 As Long

PasteCount = 41
    Range("AD2:AD1000").Copy Destination:=Range("S41" & Lastrow)
    Do While n <= 1000
        If Cells(26, n) <> 0 Then
'--------------------------------------------
            With Worksheets(1).Range("b2:b10000")
                Set c = .Find(Cells(n, 26).String, LookIn:=xlValues)
                If Not c Is Nothing Then
                    Do
                        test1 = Cells(n, 25).Value
                        test2 = c.Offset(0, -1)
                        If Abs(Cells(n, 25) - c.Offset(0, -1)) <= 100 Then
                            c.Offset(0, -1).Copy
                            Cells(PasteCount, 17).Select
                            Selection.Paste
                            PasteCount = PasteCount + 1
                            Exit Do
                        End If
                        Set c = .Find(Cells(n, 26).Value, LookIn:=xlValues)
                    Loop While Not c Is Nothing
                End If
            End With
'--------------------------------------------
        End If
        If Cells(11, n) = 0 Then
            Exit Do
        End If
    n = n + 1
    Loop
End Sub

所以这里更清楚的是代码:在SetB中查找LotID,在SetA中找到第一个(多个)对应的LotID。通过将变量偏移一个单元格然后减去两个(使用绝对值),将SetB中的日期与SetA中的日期进行比较。

如果不到100天,那就去做吧!

它没有做的事情:(。SetA中的日期显示为没有。我认为这是因为使用了变量。请帮忙!

代码在Test2(及其后)的“if test”If Abs(Cells(n, 25) - c.Offset(-1, 0)) <= 100 Then

中失败

enter image description here

1 个答案:

答案 0 :(得分:1)

您提到要将单元格放在c的左侧。在代码中,您将从上面的单元格中获取值。要查看此内容,请尝试以下代码:

Sub test()
    Dim add As String
    Dim c As Range
    Dim offsetRange As Range

    Set c = Range("B2")
    Set offsetRange = c.Offset(-1, 0)
    add = offsetRange.Address
    Debug.Print add
    Debug.Print offsetRange.Value
End Sub

Offset首先获取行,然后是列,所以你想要交换为0和-1,如下所示:

Sub test2()
    Dim add As String
    Dim c As Range
    Dim offsetRange As Range

    Set c = Range("B2")
    Set offsetRange = c.Offset(0, -1)
    add = offsetRange.Address
    Debug.Print add
    Debug.Print offsetRange.Value
End Sub

此外,您正在声明并获取变量test1和test2的值,但在进行比较时您没有使用这些值。