【问题标题】:Excel VBA How to pass range from different sheet to function properly?Excel VBA 如何从不同的工作表传递范围以正常运行?
【发布时间】:2018-05-22 03:06:37
【问题描述】:

我需要在 Excel VBA 中处理来自不同工作表的单元格范围。 这是我的代码:

Function LastDayForClient(client As String, mnth As Integer, dates As range) As String

Dim dtRow As Date
Dim dt As range

dtRow = 0

For Each dt In dates
      ' If not that month that we are looking for - go next
     If month(dt.Value) = mnth Then
       ' If not that client - go next
        If Cells(dt.Row, dt.Column + 1).Value = client Then

          If dtRow = 0 Then
            dtRow = dt.Value
          ElseIf dtRow < dt.Value Then
            dtRow = dt.Value
          End If
        End If
      End If
Next dt

LastDayForClient = Format(dtRow, "dd.mm.yyyy")

End Function

这就是我想使用公式的方式:

=LastDayForClient("Client_name";5;Diff_sheet!G6:G297)

我想我以某种错误的方式使用了传递的Range 参数,因为在不同的工作表上使用公式时我得到了错误的值。当范围在同一张纸上时,一切都很好。

【问题讨论】:

  • 为什么要使用格式,month(dt.Value2) 不需要额外的步骤就不能工作?
  • 感谢您的评论@ScottCraner!不知道我为什么那样使用它。无论如何,范围是什么?

标签: vba excel


【解决方案1】:

问题是线

If Cells(dt.Row, dt.Column + 1).Value = client Then

Cells 引用 ActiveSheet,因此您需要告诉 Cells 引用正确的工作表。

Dim wks as worksheet
set wks = dates.parent

然后

If wks.Cells(dt.Row, dt.Column + 1).Value = client Then

【讨论】:

  • 感谢@Storax 的快速回答!效果很好!
猜你喜欢
  • 1970-01-01
  • 2018-04-28
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多