[英]VBA count columns and copy them
Below code hide a certain number of rows(depending on the number of the week we are in) and shows only the cell corresponding to the current week number and cells corresponding to the future week numbers. 下面的代码隐藏了一定数量的行(取决于我们所在的星期数),并且仅显示对应于当前星期数的单元格和对应于未来星期数的单元格。
Dim test As String
test = Format(Now, "yyyy", vbMonday) & KW(Now)
For k = 3 To lastColumn
ThisWorkbook.Worksheets(PlanningTableNameUG).Columns(k).ColumnWidth = cWidth
If ThisWorkbook.Worksheets(PlanningTableNameUG).Cells(1, k).Value = test Then
today = True
On Error Resume Next
ThisWorkbook.Worksheets(PlanningTableNameUG).Columns(k - 1).Ungroup
On Error GoTo 0
ThisWorkbook.Worksheets(PlanningTableNameUG).Columns(k - 1).Group
End If
If Not today Then
On Error Resume Next
ThisWorkbook.Worksheets(PlanningTableNameUG).Columns(k).Ungroup
On Error GoTo 0
ThisWorkbook.Worksheets(PlanningTableNameUG).Columns(k).Group
ThisWorkbook.Worksheets(PlanningTableNameUG).Columns(k).Hidden = True
If Hidden = True Then
ThisWorkbook.Worksheets(PlanningTableNameUG).Columns(k).Group.Copy
ThisWorkbook.Worksheets(PlanningTableNameUG).Columns(k).Group.Insert Shift:=xlToRight
End If
Else
ThisWorkbook.Worksheets(PlanningTableNameUG).Columns(k).Hidden = False
End If
Next k
' calculate the week number
Function KW(d As Date) As Integer
Dim Tag As Long
Tag = DateSerial(Year(d + (8 - Weekday(d)) Mod 7 - 3), 1, 1)
KW = (d - Tag - 3 + (Weekday(Tag) + 1) Mod 7) \ 7 + 1
End Function
Now, I need to count how many columns were hidden and add the exact numbers of columns, example: 现在,我需要计算隐藏的列数并添加确切的列数,例如:
columns: 1,2,3,4,5,6,7,8,9,10 (column 4 is corresponding to today week number) 列:1、2、3、4、5、6、7、8、9、10(第4列与今天的星期几相对应)
I hide: 1,2,3 because there are in the past weeks, and want to add 11,12, 13, together with the week number corresponding for them, but not more than 1 year from current date. 我隐藏了:1,2,3,因为过去有几周,并且想要加上11,12,13以及它们对应的星期数,但从当前日期起不超过1年。
Count of the weeks starts at the begging of the current year. 周数从当年的乞讨开始。
To count hidden columns in used range of ThisWorkbook.Worksheets(PlanningTableNameUG): 要计算ThisWorkbook.Worksheets(PlanningTableNameUG)的使用范围内的隐藏列:
Dim col As Range
Dim cnt As Long
For Each col In ThisWorkbook.Worksheets(PlanningTableNameUG).UsedRange
Debug.Print col.EntireColumn.Hidden
cnt = cnt - col.EntireColumn.Hidden
Next col
EntireColumn.Hidden returns True if is hidden. 如果被隐藏,EntireColumn.Hidden返回True。 True is -1 in VBA, that is why i deduct it from the counter to get positive value.
在VBA中True为-1,这就是为什么我从计数器中减去以获得正值。
When hiding the columns you could add an integer variable that increases by one then use this variable to add that many new columns. 隐藏列时,您可以添加一个整数变量,该变量增加一,然后使用此变量添加许多新列。
Then to add the week number, use the last column with the week number on it and add one to it for each of the new columns... 然后要添加周数,请在最后一列上加上周数,并为每个新列添加一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.