繁体   English   中英

让 Excel 根据日期将数据从一个单元格复制到另一个单元格

[英]Getting Excel to Copy Data From One Cell to Another Depending on Date

提前道歉,因为这是我第一次在本网站上发布内容,我不是最擅长解释问题的人。

我有一个电子表格,其中包含生产数据,例如每日计量表、每月计量表等。这些值是通过使用 Rockwell VantagePoint Excel 加载项从 PLC 添加 TAGS 来更新的(如果您不熟悉这一点,这部分无关紧要)不是我挣扎的)

我需要在月末将数据从一个单元格复制到同一工作表上的另一个单元格。 基本上,每月的 Meters 字段需要在月底复制到另一个单元格中,以记录该月运行的仪表。 每月仪表运行在月底重置回 0。

基本上我需要在该月末将 J7 中的值复制到 W 列中的相应月份中。 如果它可以忽略年份,那将是有利的,因为我不需要它来保留旧值,这意味着我只需要一列。

我在 MS-Excel 和 VBA 方面有一些经验,但主要是在 MS-Access 方面从未在 MS-Excel 中使用过。 如果可以尽可能简单地解释答案并亲自动手,将不胜感激。

在谷歌搜索问题后,我遇到了这个公式并更改了范围以适合我的工作表,但 Excel 不喜欢它说它包含错误

=QUERY( A1:B6; "select B where A =date """&TEXT(TODAY();"yyyy-mm-dd")&""" "; 0

如果我没有正确解释自己,再次抱歉。

电子表格的屏幕抓取

如果您的工作簿不能保证在每个月底打开,我会在每次打开时更新该值,例如(应该放在 ThisWorkbook 中):

'Runs when you open the workbook
Private Sub Workbook_Open()
    'Loops through U3 to the last used cell in that column
    For Each c In Range(Cells(3, 21), Cells(Rows.Count, 21).End(xlUp))
        'Applies the J7 value to the current month and exits the sub
        If Month(c) = Month(Now) Then c.Offset(, 2).Value = [J7]: Exit Sub
    Next c
End Sub

此外,这并不重要,但我会在 U3:U14 中应用以下公式以始终获得正确的日期:

=EOMONTH(DATE(YEAR(TODAY()),ROW()-2,15),0)

好的,我仍然不太确定问题是什么,我比 Excel VBA 更了解 Access VBA,但这里有一些可能有助于找到解决方案的内容。

您可以创建一个返回布尔值的检查日期函数:

Public Function EoMonthCheck() As Boolean

    Dim eo_month As Date, today As Date

    eo_month = Format(WorksheetFunction.EoMonth(Now(), 0), "yyyy-MM-dd")
    today = Format(Now(), "yyyy-MM-dd")

    If today = eo_month Then
        EoMonthCheck = True
    Else
        EoMonthCheck = False
    End If


End Function

并且,要向“W”列添加一个值,我们可能会使用以下内容:

Public Function AppendValue(Optional target_cell As String = "J7")
''' This could be a subroutine, too, I guess, since we're not returning anything.

    Dim i As Integer

    ''' Activate whatever sheet you want to work with
    Worksheets("Sheet1").Activate

    If EoMonthCheck() = True Then
        ''' Look up the bottom of the  'W' column and find the first non-empty cell
        ''' Add 1 to that cell to get you to the next cell (the first empty one).
        i = Cells(Rows.Count, "W").End(xlUp).Row + 1

        ''' Set the value of that empty cell in the 'W' column to the value of 'J7'
        ''' which will happen after we evaluate whether it is the end of the month.
        Cells(i, "W").Value = Range(target_cell).Value

End If

然后,您可能会在每次打开工作簿时触发它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM