【问题标题】:Excel VBA - Date until last rowExcel VBA - 直到最后一行的日期
【发布时间】:2017-04-27 03:39:26
【问题描述】:

我目前正在努力实现以下目标:

A 列中有数据(例如,Orange、Apple、Mango),而 B 列是空的。我想实现一个框,在输入日期后它会自动填充一个范围。

到目前为止,这是我的代码:

Public Sub DATERES()
Dim strUserResponse As String

strUserResponse = InputBox("Enter Date")

ActiveSheet.Range("B1:B100").Value = strUserResponse

End Sub

到目前为止一切都很好,但是,我的问题是 A 中的数据有时会在 1 到 500-600 之间变化。因此,我想对其进行修改,使其首先检查 A 列,并且只在 B 列中输入日期直到最后一行,而不是给它更大的范围(如 B1:B1000)。

感谢任何帮助和建议。

祝你有美好的一天!

【问题讨论】:

    标签: excel vba date autofill


    【解决方案1】:
    Public Sub DATERES()
    Dim strUserResponse As String
    dim lastrow as long
    
    strUserResponse = InputBox("Enter Date")
    
    lastrow = Cells(Rows.Count,1).end(xlup).row 'the 1 will get the last row for column A. Change if needed
    
    
    ActiveSheet.Range("B1:B"& lastrow).Value = strUserResponse
    
    End Sub
    

    使用引用的SheetsRanges 代替ActiveSheet 更安全。

    ' modify "Sheet1" to your sheet's name
    With Sheets("Sheet1")
    
        lastrow = .Cells(.Rows.count, 1).End(xlUp).Row ' the 1 will get the last row for column A. Change if needed
    
        .Range("B1:B" & lastrow).Value = strUserResponse
    End With
    

    【讨论】:

    • 您的 lastrow 正在查看 B 列,该列是空的(阅读帖子),您需要用日期填充它(在 A 列中)。所以你需要在 A 列中搜索最后一行。
    • 感谢您的快速回复!! :) 效果很好!
    • @Moacir 只是为了确保您没有在代码中间弄乱引用,我会在最后一行之前使用With ActiveSheet。或者更好的是使用引用对象With Sheets("yoursheetname") ..
    • 你的意思是像lastrow = ActiveSheet.Cells(Rows.Count,1).end(xlup).row?或者With ActiveSheet lastrow = Cells(Rows.Count,1).end(xlup).row Range("B1:B"& lastrow).Value = strUserResponse End With
    • @llorcs 在下面的回答中阅读了我的提示,它将帮助您节省用户在InputBox 中输入错误数据的时间
    【解决方案2】:

    仅供参考,如果您希望 ImputBox 强制用户以 Date 格式输入值,请使用以下行:

    Dim strUserResponse As Date
    
    strUserResponse = Application.InputBox("Enter Date", , FormatDateTime(Date, vbShortDate), Type:=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 2022-10-24
      相关资源
      最近更新 更多