【发布时间】:2015-06-23 08:36:52
【问题描述】:
目标:拥有一个宏,该宏在一张表中包含内容的行,由空行分隔,具体取决于其他表的值。以下是最终输出的样子:
现在的情况(手动):我转到工作表 3,查看存在哪些类别,然后在带红色背景的工作表 1 上手动添加它们。然后,我转到工作表 2,查看每个类别存在多少子项,然后在工作表 1 中手动添加那么多行。
第 2 页的图片:
第 3 页的图片(类别)
宏的情况:我运行一个宏,然后根据表 3 创建类别,并根据表 2 中的项目数在这些类别之间创建空行。
到目前为止,这是我的代码:
Sub AddingCategories()
'
' AddingCategories Macro
'
' here we copy the categories from the Categories sheet
Sheets("Categories").Select 'we select the sheet where the categories are
Range("A1").Select 'we select the first cell with content
Range(Selection, Selection.End(xlDown)).Select 'we can select all categories with content
Application.CutCopyMode = False
Selection.Copy 'we copy the content
Sheets("Timeschedule2").Select 'we go to the destination sheet
Range("B11").Select 'We select the first row where we want content
ActiveSheet.Paste
'Here we format them to red
Range("A11:B25").Select 'since we just copied content, we need to have the cells with the formatting we want (in this case red)
Application.CutCopyMode = False
With Selection.Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End With
With Selection.Font
.ColorIndex = xlAutomatic
.TintAndShade = 0
End With
'Here we delete all rows without content
Range("B11:B30").Select
Selection.SpecialCells(xlCellTypeBlanks).Select
ActiveWindow.SmallScroll Down:=-6
Selection.EntireRow.Delete
'Here we add the rows. Since we want to specify a number of rows to add, we first calculate this value using a countif function
'this will tell us how many rows we need to add and we have it in Categories!C1. To add that many rows, we use a loop
For i = 1 To Worksheets("Categories").Range("C1")
Worksheets("Timeschedule2").Select
Rows("12:12").Select
Selection.Insert
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Next i
End Sub
使用这段代码,我非常自豪地创建了类别并设法为第一个类别创建了行数。 我现在的问题是我不知道如何创建将自动为所有类别执行此操作的循环(要执行第一个,我指定将它们添加到第 12:12 行;但我无法提前知道他们应该在哪里添加下一个新行,也不是循环多少次,因为类别的数量会因项目而异) 我一直在使用 Do until IsEmpty、Do While、For 等进行搜索,但我无法弄清楚。
你会怎么做呢?如何改进现有代码?
我知道我的代码可能很不优雅,对此深表歉意! 我主要对学习如何编程 VBA 感兴趣,而不是让这个特定的宏工作,所以如果你能像我是一个 5 岁的非程序员一样向我解释,我将不胜感激。
【问题讨论】:
-
在给定示例中选择行
12的逻辑是什么?最终,要告诉计算机这样做,您需要有一些确定性的方法来识别行。另外,如果可能,您能否制作第二张包含行号和列号的图片? -
我同意。 12:12 是我可以使用的第一行(类别应该从哪里开始),但如果以确定的方式识别它会更好。你对我如何做到这一点有什么建议吗?这是Sheet 2的图片postimg.org/image/pkbtit8dn这是Sheet 3(类别)的图片postimg.org/image/ei6qkdeaz/94034406
-
由于这是基于
COUNTIF,您可以在VBA 中使用Application.WorksheetFunction.CountIf来获得相同的数字。您也可以按照自己的方式处理这些工作表上的当前结果,并在 VBA 中使用公式结果。由于这是基于标签匹配,您可以使用Application.WorksheetFunction.Match来确定给定项目/子项目在工作表上的位置。 -
谢谢拜伦!这有助于我进一步
-
感谢@ByronWall 的提示,他们帮助我找到了答案 :)