我正在尝试选择工作表以另存为 csv,之前使用定义每个工作表名称的数组,但我必须每个月更新选项卡名称。
我有一个选项卡,其中的工作表名称已定义为“TabNames”,任何人都可以帮助我处理代码,因为我遇到了不匹配错误
子 EPMI()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim ws As Worksheet
Dim Month As String
Dim vArray() As Variant
vArray = Range("TabNames")
Sheets(vArray("TabNames")).Select
要根据名为“TabNames”的范围中定义的工作表名称列表将特定工作表另存为 CSV 文件,您需要稍微修改代码以确保正确访问该范围并适当处理它。
这是代码的修订版本:
Sub EPMI()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim ws As Worksheet
Dim sheetName As String
Dim tabNames As Range
Dim cell As Range
' Set the range for the named range "TabNames"
Set tabNames = ThisWorkbook.Names("TabNames").RefersToRange
' Loop through each cell in the named range
For Each cell In tabNames
sheetName = cell.Value ' Get the sheet name from the cell
' Check if the worksheet exists
On Error Resume Next
Set ws = ThisWorkbook.Worksheets(sheetName)
On Error GoTo 0
If Not ws Is Nothing Then
' Save the worksheet as CSV
ws.Copy ' Copy the worksheet to a new workbook
With ActiveWorkbook
.SaveAs Filename:=ThisWorkbook.Path & "\" & sheetName & ".csv", FileFormat:=xlCSV
.Close False ' Close the new workbook without saving changes
End With
Else
MsgBox "Sheet " & sheetName & " does not exist!", vbExclamation
End If
Set ws = Nothing ' Reset ws for the next iteration
Next cell
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
设置命名范围:
Set tabNames = ThisWorkbook.Names("TabNames").RefersToRange
行获取“TabNames”命名范围中定义的工作表名称范围。
循环访问每个工作表名称:
For Each cell In tabNames
循环迭代指定范围中的每个单元格。
检查工作表是否存在:它使用错误处理来检查工作表是否存在。如果是,则继续;如果没有,它会显示一个消息框。
复制并另存为 CSV:将每张工作表复制到新工作簿,然后将其另存为 CSV 文件,与原始工作簿位于同一目录中。新工作簿将关闭,且不保存其他更改。
重置工作表变量:
Set ws = Nothing
确保为下一次迭代重置变量。