简体   繁体   English

更改列中所有单元格的值

[英]Change value of all cells in a column

I need to write code that reformats text messages in an excel file using VBA.我需要编写代码,使用 VBA 在 excel 文件中重新格式化文本消息。 One column has the dates each text was sent/received.一列包含每个文本发送/接收的日期。 I need to change this column to say "Day 1", "Day 2", instead.我需要将此列更改为“第 1 天”、“第 2 天”。 So for example, 11/3/19 would be "Day 1" 11/3/19 would be "Day 1" 11/4/19 would be "Day 2" 11/6/19 would be "Day 4"例如,11/3/19 将是“第 1 天” 11/3/19 将是“第 1 天” 11/4/19 将是“第 2 天” 11/6/19 将是“第 4 天”

To do this, I want to subtract each date by the first date and add 1. I can do this per individual cell:为此,我想用第一个日期减去每个日期并加 1。我可以按单个单元格执行此操作:

Sub Days()
Range("M2").Value = "Day " + CStr(Range("E2").Value - Range("E2").Value + 1)
Range("M3").Value = "Day " + CStr(Range("E3").Value - Range("E2").Value + 1)
Range("M4").Value = "Day " + CStr(Range("E4").Value - Range("E2").Value + 1)
End Sub

I want it done to every cell in column E. This was my attempt:我希望它对 E 列中的每个单元格进行。这是我的尝试:

Sub Days()
Columns("M:M").Value = "Day " + CStr(Columns("E:E").Value - Range("E2").Value + 1)
(End Sub)

How would I adjust the code to make it work?我将如何调整代码以使其工作?

If you really want this to be VBA, here's one solution, leveraging the formula already provided in comments:如果你真的希望这是 VBA,这里有一个解决方案,利用评论中已经提供的公式:

Sub Days()
    With ActiveSheet
        Dim lastRow As Long
        lastRow = .Cells(.Rows.Count, "E").End(xlUp).Row

        .Range("M2:M" & lastRow).Formula = "=""Day "" & E2 - $E$2 + 1"
        .Range("M2:M" & lastRow).Value = .Range("M2:M" & lastRow).Value
    End With
End Sub

Do not do the full column.不要做整列。 Find the last cell with data in column E then use Evaluate:找到 E 列中包含数据的最后一个单元格,然后使用 Evaluate:

Sub Days()
    With Worksheets("Sheet2")
        Dim lstRow As Long
        lstRow = .Cells(.Rows.Count, 5).End(xlUp).Row

        .Range("M2:M" & lstRow) = .Evaluate("INDEX(""Day "" & E2:E" & lstRow & " - E2 + 1,)")
    End With
End Sub

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

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