繁体   English   中英

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

[英]How to select column and display its current format using VBA Macro?


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


<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的初学者。
提前致谢。

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

您提到您是VBA初学者,请采用以下答案进行教育用途,然后开始着手准备所需的工具。 请注意,如果不回答,因为没有包含的信息你的问题, 仍然回答了你的问题,缺少的信息应该形成一个新的问题的一部分。 也就是说,让此功能启动并运行。

从您写的内容来看,我的要求是:

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

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

目标的伪代码:-

对于Worksheet Workbook每个Worksheet

..对于Worksheet每一Column

...如果该Column包含日期, Column要求设置其格式

..处理下一column

处理下一个Worksheet

我们通过使用变量引用Worksheet并使用循环(对于每一个)更改引用来实现。 列也是如此。

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行,并且各列之间没有空格,但是这些是准备就绪时可以解决的单独问题。

暂无
暂无

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

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