我有一段代码应该按名称检查工作表是否存在。如果工作表存在,则有一些复制和过去功能,如果工作表不存在,则它将创建并遵循相同的复制过去功能。我无法获得正确的布尔值以返回主子。布尔值始终注册为 false(我知道这是默认值)。我尝试了几种不同的方法来纠正这个问题,但我仍然遇到问题。我真的可以使用一些帮助,这可能是一个简单的修复。
Sub BreakOutCategories()
Dim catSheet As Worksheet
Dim catName As String
Dim Range1 As Range
Dim gRange As Range
Dim toSheet As Worksheet
Dim CheckSheet As Boolean
Dim CreateSheet As Boolean
Dim i As Long
Set catSheet = Sheets("MasterList")
Set Range1 = catSheet.Range("A1", catSheet.Range("A1").End(xlDown))
For Each gRange In Range1
i = 0
catName = gRange.Value
CheckMySheet (catName)
If CheckSheet = True Then
toSheet = Sheets(gRange.Value)
gRange.Offset(0, 1).Copy
toSheet.Range("A1", toSheet.Range("A1").End(xlDown)).Offset(1, 0).Paste
gRange.Offset(0, 1).Copy
toSheet.Range("E1", toSheet.Range("E1").End(xlDown)).Offset(1, 0).Paste
gRange.Offset(0, 2).Copy
toSheet.Range("B1", toSheet.Range("B1").End(xlDown)).Offset(1, 0).Paste
gRange.Offset(0, 2).Copy
toSheet.Range("F1", toSheet.Range("F1").End(xlDown)).Offset(1, 0).Paste
ElseIf CheckSheet = False Then
CreateMySheet catName
toSheet = (gRange.Value)
gRange.Offset(0, 1).Copy
toSheet.Range("A1", toSheet.Range("A1").End(xlDown)).Offset(1, 0).Paste
gRange.Offset(0, 1).Copy
toSheet.Range("E1", toSheet.Range("E1").End(xlDown)).Offset(1, 0).Paste
gRange.Offset(0, 2).Copy
toSheet.Range("B1", toSheet.Range("B1").End(xlDown)).Offset(1, 0).Paste
gRange.Offset(0, 2).Copy
toSheet.Range("F1", toSheet.Range("F1").End(xlDown)).Offset(1, 0).Paste
End If
Next gRange
End Sub
Public Function CheckMySheet(ByVal catName As String) As Boolean
Dim theSheet As Worksheet
Dim CheckSheet As Boolean
For Each theSheet In ThisWorkbook.Sheets
If theSheet.Name = catName Then
CheckSheet = True
Exit For
End If
Next theSheet
End Function
Public Function CreateMySheet(ByVal catName As String) As Boolean
Dim catSheet As Worksheet
Dim newSheet As Worksheet
Dim Range1 As Range
Dim gRange As Range
Set catSheet = Sheets("MasterList")
Set Range1 = catSheet.Range("A1", catSheet.Range("A1").End(xlDown))
Set newSheet = Sheets.Add(After:=Sheets("Cover"))
newSheet.Name = catName
newSheet.Range("A1") = "Line"
newSheet.Range("E1") = "Line"
newSheet.Range("B1") = "Item"
newSheet.Range("F1") = "Item"
newSheet.Range("C1") = "Units"
newSheet.Range("G1") = "Sales"
CreateMySheet = True
End Function
我已经完整地发布了代码,试图很好地描述我想要完成的工作。我还在考虑一个Do Until
循环,CreateMySheet catName
以再次检查工作表是否存在,以防止代码向前移动,直到工作表完全创建为止。
谢谢!