使用列标题进行动态范围选择

时间:2018-10-16 15:13:46

标签: excel

我是VBA的新人,我需要您的帮助。

我有一个带有动态表的excel电子表格(标题在第4行)。导入到表中的数据包含Excel无法格式化为m-d-yyyy的日期值(2018年9月5日下午6:11:17 PM EDT)。格式化日期的唯一方法是删除“逗号”,“ EDT”和“ EST”值。该宏将运行并按预期工作。

现在,我的挑战是修改此宏(VBA)以查找列标题名称,而不是整个列。随着我不断被要求在表格中添加一列。列名称为“目标终止日期”,“实际终止日期”,“创建日期”,“上次更新日期”,“认证日期”和“认证到期日期”

所有数据都填充在第5行中,这是一个动态表。

这是我当前的代码

Sub ConvertDateFormat()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+Shift+D
'
    Range("V:V,W:W,Z:Z,AA:AA,AC:AC,AD:AD").Select
    Range("V5").Activate
    Selection.NumberFormat = "m/d/yyyy"
    Selection.Replace What:=",", Replacement:=" ", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Selection.Replace What:="EDT", Replacement:=" ", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Selection.Replace What:="EST", Replacement:=" ", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub

2 个答案:

答案 0 :(得分:0)

您可以直接引用表格及其列,而无需使用列字母。

Dim tbl As ListObject 'this will be the table
Dim rngData as Range

Set tbl = ActiveSheet.ListObjects("name_of_your_table")
Set rngData = tbl.ListColumns("Target Decomm Date").DataBodyRange
rngData.NumberFormat = "m/d/yyyy"
rngData.Replace [.....]

您可以使用数组循环遍历所有不同的列名,但由于它在网络上有据可查,例如How can I use a for each loop on an array?

答案 1 :(得分:0)

这是我的结束脚本,效果很好。

Sub FormatDate()
'
Dim tbl As ListObject 'this will be the table
Dim rng1, rng2, rng3, rng4, rng5, rng6, rngM As Range

Set tbl = ActiveSheet.ListObjects("tblProductList")
Set rng1 = tbl.ListColumns("Target Decomm Date").DataBodyRange
Set rng2 = tbl.ListColumns("Actual Decomm Date").DataBodyRange
Set rng3 = tbl.ListColumns("Created Date").DataBodyRange
Set rng4 = tbl.ListColumns("Last Updated Date").DataBodyRange
Set rng5 = tbl.ListColumns("Accreditation Date").DataBodyRange
Set rng6 = tbl.ListColumns("Accreditation expiry Date").DataBodyRange
Set rngM = Union(rng1, rng2, rng3, rng4, rng5, rng6)
rngM.NumberFormat = "m/d/yyyy"
rngM.Replace What:=",", Replacement:=" ", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
rngM.Replace What:="EDT", Replacement:=" ", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
rngM.Replace What:="EST", Replacement:=" ", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
End Sub