【问题标题】:How to select column and display its current format using VBA Macro?如何使用 VBA 宏选择列并显示其当前格式?
【发布时间】:2016-05-26 09:38:10
【问题描述】:


请在下面找到我无法找到任何解决方案的要求:

1.从工作簿迭代工作表
2. 使用当前格式/列类型查找所有包含日期​​值的列
(这是一个技巧。工作表不是静态的,它可以包含任意数量的包含日期值的列。包含日期值的列可能有任何名称。这样的工作表可以多于一张)
3. 如果“标志”值为“y”,则在日期列上应用宏以进行日期格式(在宏下方)

<code>
Sub FormatDate()
    If wksSecDist.Range("Flag").value = "y" Then
        LastRowColA = Range("X" & Rows.Count).End(xlUp).Row
        ' Here I am finding total number of rows in column X
        wksSecDist.Range("X2", "X" & LastRowColA).NumberFormat = "dd/mmm/yyyy"
        ' Here applying specified date format to Range("X2", "X10") [if last row index for column X is 10]
    End If
End Sub
</code>


我只是 VBA 的初学者。
提前致谢。

【问题讨论】:

    标签: vba excel macros


    【解决方案1】:

    我怀疑您没有在 Internet 上找到解决方案,因为您只是在寻找解决方案,而不是构建您自己的解决方案所需的部分。

    您提到您是 VBA 初学者,请采用以下答案以用于教育用途,并开始将您带到您需要工具的地方。请注意,如果由于未包含信息而无法回答您的问题,它仍然回答了您的问题,缺失的信息应构成新问题的一部分。也就是说,让我们启动并运行此功能。

    根据您所写的内容,我将要求解释为:-

    1. 查看工作簿中的所有工作表('工作表可以有多个')
    2. 检查每一列以查看它是否包含日期值
    3. 如果是,请将整列设置为特定格式

    完成此操作需要的是迭代(循环),一个循环遍历所有工作表,另一个循环遍历所有列:-

    目标的伪代码:-

    .对于Workbook中的每个Worksheet

    ..对于Worksheet中的每个Column

    ...如果Column 包含日期,则根据需要对其进行格式化

    ..处理下一个column

    .处理下一个Worksheet

    我们使用一个变量来引用 Worksheet 并使用循环 (For Each) 来更改引用来实现这一点。列也是如此。

    Public Sub Sample()
    Dim WkSht       As Excel.Worksheet
    Dim LngCols     As Long
    Dim LngCol      As Long
    
    'This loop will process the code inside it against every worksheet in this Workbook
    For Each WkSht In ThisWorkbook.Worksheets
    
        'Go to the top right of the worksheet and then come in, this finds the last used column
        LngCols = WkSht.Range(WkSht.Cells(1, WkSht.Columns.Count).Address).End(xlToLeft).Column
    
        'This loop will process the code inside it against every column in the worksheet
        For LngCol = 1 To LngCols
    
            'If the first cell contains a date then we should format the column
            If IsDate(WkSht.Cells(2, LngCol)) Then
    
                'Set right to the bottom of the sheet
                WkSht.Range(WkSht.Cells(2, LngCol), WkSht.Cells(WkSht.Rows.Count, LngCol)).NumberFormat = "dd/mmm/yyyy"
    
            End If
    
        Next
    
    Next
    
    End Sub
    

    希望这一切都说得通,这样做的前提是标题行始终是第 1 行并且列中没有间隙,但这些是您可以在准备好时解决的单独问题。

    【讨论】:

    • 我错过的是“IsDate()”。我找不到如何检查日期格式的列。我认为这会对我有所帮助。谢谢加里!!
    • @Shrikant 不客气,很高兴它有帮助。我忘了在列表中添加它还假设数据从第 2 行开始。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    相关资源
    最近更新 更多