【发布时间】:2015-10-04 17:57:55
【问题描述】:
我实际上是一个 vba 初学者并创建了我的第一个代码,但我需要做得更灵活...... 当我使用 makro 时,我想选择更多的 excel 表。实际上我只使用名为“sector_share_se”的工作表,但我如何为选定的工作表运行相同的 makro,例如“sheet_1”、“sheet_5”和其他?此外,有没有办法计算一个 cloumn 中的填充行?然后我可以创建一个灵活的范围,而不是 Range("A400") 和 Range("A4:A400")。
我在这里做了什么?
我想在每月的 scala 上设置年度数据。我在填充的行之间创建了 11 个空行,并从名为“MSCI”的表中复制了月度刻度。最后一步是用 NA 填充空单元格(以每行 11 个 NA 值的方式)
Sub Year_to_Month()
' emtpy space in selected sheet
Sheets("sector_share_se").Select
Dim i As Long
i = sector_share_se
For i = Range("A400").End(xlUp).Row To 5 Step -1
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Next i
' Create time frequency
Sheets("MSCI").Range("A4:A400").Copy
Sheets("sector_share_se").Range("A4:A400").PasteSpecial
' replace empty with NA
Range("A4:AI310").Select
Selection.Replace What:="", Replacement:="NA", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
提前致谢 勒内
使用@MatthewD 的信息进行编辑:
' I understand iIndex as number of the excel sheet and it is possible to
' adress the correct sheet with it but how can I use here more sheets that I
' can enter only the Number (or Name) of the sheet e.g. iIndex = 1,2,3,7,9,15
Dim lRow As long
Dim iIndex As long
For iIndex = 1 To ActiveWorkbook.Worksheets.count
Set ws = Worksheets(iIndex)
For ws = Range("A400").End(xlUp).Row To 5 Step -1
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Cells(i, 1).EntireRow.Insert
Next i
' I hope that I set the maximum lenght with "ws.UsedRange.Rows.count"
' and copy it row by row
For lRow = 1 To ws.UsedRange.Rows.count
Sheets("MSCI").Range("1:lRow").Copy
Sheets("banking_sector").Range("1:lRow").PasteSpecial
Next lRow
' I think that this is quiet okay (I recorded it only), it should
' select the hole data and replace the NA's
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Replace What:="", Replacement:="NA", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
【问题讨论】: