如何使用VBA宏选择列并显示其当前格式?

时间:2016-05-26 09:38:10

标签: excel vba excel-vba macros


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

1。从工作簿中迭代workSheet 2.使用当前格式/列类型查找包含日期值的所有列
(这是一个技巧。工作表不是静态的,它可以包含任意数量的包含日期值的列。包含日期值的列可能有任何名称。这样的工作表可以多于一个)
3.在日期列上应用宏以进行日期格式化(在宏下面),如果" Flag"价值是" 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的初学者 提前谢谢。

1 个答案:

答案 0 :(得分:2)

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

你提到你是VBA的初学者,请把以下答案用于教育用途,并开始帮助你找到你需要的工具。请注意,如果由于未包含的信息而无法回答您的问题,则 仍然会回答您的问题,并且缺少的信息应构成新问题的一部分。也就是说,让我们启动并运行此功能。

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

  1. 查看工作簿中的所有工作表(&#39; 工作表可以多个数字&#39;)
  2. 检查每一列以查看它是否包含日期值
  3. 如果是,请将整列设置为特定格式
  4. 实现这一点需要的是迭代(循环),一个循环遍历所有工作表,另一个循环遍历所有列: -

    目标的伪代码: -

    。对于Worksheet

    中的每个Workbook

    ..对于Column

    中的每个Worksheet

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

    ..处理下一个column

    .Process next 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行并且列中没有间隙,但这些是您准备好时可以处理的单独问题。