Vba 如何在excel中检查不同的工作表名称并添加新的工作表名称,以防它不';不存在
我正在将我的数据从MS Project导出到MS Excel(始终使用给定名称的单个预定义文件,例如XYZ.xlsx),并希望在Excel中为项目中的每个工作流创建不同的工作表。而且工作流的数量将来可能会增加,因此我必须保持它的动态性 到目前为止,我的代码进行导出,但我还希望它检查工作流是否已经存在, -如果是,请删除该工作表中的所有数据,并将新数据粘贴到XYZ文件中。 -如果否,请在XYZ文件中创建新工作表并将数据粘贴到其中 有人能帮我吗,因为我快完成了 我正在使用的代码Vba 如何在excel中检查不同的工作表名称并添加新的工作表名称,以防它不';不存在,vba,excel,ms-project,Vba,Excel,Ms Project,我正在将我的数据从MS Project导出到MS Excel(始终使用给定名称的单个预定义文件,例如XYZ.xlsx),并希望在Excel中为项目中的每个工作流创建不同的工作表。而且工作流的数量将来可能会增加,因此我必须保持它的动态性 到目前为止,我的代码进行导出,但我还希望它检查工作流是否已经存在, -如果是,请删除该工作表中的所有数据,并将新数据粘贴到XYZ文件中。 -如果否,请在XYZ文件中创建新工作表并将数据粘贴到其中 有人能帮我吗,因为我快完成了 我正在使用的代码 Set tsks =
Set tsks = ThisProject.Tasks
For Each t In tsks
If Not t Is Nothing Then
If t.OutlineLevel > 1 Then
If t.OutlineLevel = 2 Then
If ExcelRowCounter > 2 Then
'Finish formatting the sheet we just finished
For i = 1 To 7
xlSheet.Columns(i).AutoFit
Next i
End If
'Add Excel sheet, name it and define column headers
AppActivate ExcelAppTitle
Set xlSheet = xlBook.Worksheets.Add
ExcelSheetName = Left(Replace(t.Name, "&", "and"), 30)
xlSheet.Name = ExcelSheetName
xlSheet.Cells(1, 1).Value = "Task Name"
xlSheet.Cells(1, 2).Value = "Duration (days)"
xlSheet.Cells(1, 3).Value = "Start Date"
xlSheet.Cells(1, 4).Value = "Finish Date"
xlSheet.Cells(1, 5).Value = "Workstream Group"
xlSheet.Cells(1, 6).Value = "% Complete"
xlSheet.Cells(1, 7).Value = "Status"
xlSheet.Range(xlSheet.Cells(1, 1), xlSheet.Cells(1, 7)).Font.Bold = True
ExcelRowCounter = 2
End If
xlSheet.Cells(ExcelRowCounter, 1).Value = t.Name
xlSheet.Cells(ExcelRowCounter, 2).Value = t.Duration / (8 * 60)
xlSheet.Cells(ExcelRowCounter, 3).Value = Format(t.Start, "mm/dd/yyyy")
xlSheet.Cells(ExcelRowCounter, 4).Value = Format(t.Finish, "mm/dd/yyyy")
xlSheet.Cells(ExcelRowCounter, 5).Value = t.Text1
xlSheet.Cells(ExcelRowCounter, 6).Value = t.PercentComplete
xlSheet.Cells(ExcelRowCounter, 7).Value = t.Number1
xlSheet.Cells(ExcelRowCounter, 1).IndentLevel = 2 * (t.OutlineLevel - 2)
If t.Summary = "True" Then
xlSheet.Range(xlSheet.Cells(ExcelRowCounter, 1), xlSheet.Cells(ExcelRowCounter, 6)).Font.Bold = True
End If
ExcelRowCounter = ExcelRowCounter + 1
End If
End If
Next t
For i = 1 To 7
xlSheet.Columns(i).AutoFit
Next i
以下是一个简单的方法:
Function AddOrGetWorksheet(withName As String) As Worksheet
Dim found As Boolean
found = False
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
If (LCase(ws.Name) = LCase(withName)) Then
found = True
Set AddOrGetWorksheet = ws
Exit For
End If
Next
If (Not found) Then
Set AddOrGetWorksheet = ActiveWorkbook.Sheets.Add()
AddOrGetWorksheet.Name = withName
End If
End Function
那么你到底在问什么呢?事实上我是VBA的新手,我想问我应该如何添加检查工作表是否已经存在并具有工作流名称的条件,如果不存在,如何添加具有该名称的新工作表。好的,你能将问题简化为这一点吗?您提供的代码似乎在很大程度上(如果不是完全)不相关。谢谢您的建议。我知道我很晚才回复,但我改变了我的方法,没有遵循这个方法。