【问题标题】:VLookup in VBA for loop failing after first passVBA中的VLookup for循环在第一次通过后失败
【发布时间】:2016-12-19 13:47:56
【问题描述】:

我正在尝试在 VBA 中使用 FOR 循环来遍历工作表并使用 VLookup 来确定基于每个范围的值。基本上,工作表设置在我有 14 个范围的地方,每个范围是 2 列(日期和值),设置如下: Sample Data

此代码循环遍历每个范围并执行 VLookup 以返回值,如果没有值则返回 -1。

我遇到的问题是这适用于第一行数据,但之后的所有行都返回 -1。

Sub Format(inSheet As String, outSheet As String, lastAvail as Date, maxRows as Long)
Do While curDate <= lastAvail
    For x = 2 To (maxRows - 1) * 2 Step 2
        ' Get value of current data series
        Sheets(inSheet).Activate
        Range(Cells(8, x - 1), Cells(8, x)).Select
        Range(Selection, Selection.End(xlDown)).Select
        Set lookupRange = Selection
        val = Application.VLookup(curDate, Worksheets(inSheet).Range(lookupRange.Address), 2, False)
            Sheets(outSheet).Activate
            If IsError(val) Then
                Cells(curRow, x / 2 + 1).Value = -1
            ElseIf IsNumeric(val) Then
                Cells(curRow, x / 2 + 1).Value = val
            Else
                Cells(curRow, x / 2 + 1).Value = Null
            End If
    Next

    curDate = DateAdd("m", 1, curDate)
    Cells(curRow, maxRows + 1).Value = curDate - 1
    curRow = curRow + 1
    val = ""
Loop

【问题讨论】:

  • 您是否尝试过单步执行以查看循环中发生了什么?
  • 我不是 100% 确定,但您不是在 curDate = DateAdd("m", 1, curDate) 上添加一个月,而您的数据样本只有同一个月(一月)的一组天吗?
  • 另外,它是best to avoid .Select,一般来说可能会有帮助。
  • 除了其他任何东西之外,您正在更改循环的每次迭代的查找范围:您真的只想更改查找 value (您在表中搜索的内容)。
  • @BruceWayne 只是出于好奇,你有什么建议?我想不出一种更优雅的方式来捕捉范围

标签: excel for-loop vlookup vba


【解决方案1】:

感谢你们的帮助,事实证明,当我用 DateAdd 增加 curDate 时,它​​会改变格式,所以 VLookup 无法识别它与实际数据匹配。我在VLookup 之前将curDate 转换为Long,一切都自行解决了。

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 2013-10-04
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多