在macos系统上使用vba把excel的每个工作表另存为csv文件

Sub ExportWorksheetsAsCSVOnMac()
    Dim ws As Worksheet
    Dim newWb As Workbook
    Dim newWs As Worksheet
    Dim savePath As String
    Dim fileName As String
    Dim filePermissionCandidates
    
    '导出所有工作表到单独的csv文件,并以工作表命名,保存路径为当前excel文件所在目录下的导出的csv
    savePath = ThisWorkbook.Path & "/"
    filePermissionCandidates = Array(savePath)
    fileAccessGranted = GrantAccessToMultipleFiles(filePermissionCandidates)   '给要保存的文件所在文件夹授权,不然在保存时会出现无法访问只读文件
    If Not fileAccessGranted Then
        MsgBox savePath & ",授权失败"
        Exit Sub
    End If
    ' 创建新的工作簿
    Set newWb = Workbooks.Add
    
    ' 遍历原工作簿中的所有工作表
    For Each ws In ThisWorkbook.Worksheets
        ' 复制工作表到新工作簿
        newWb.Worksheets(1).Name = "asdfonmasdofmasodfmo"
        ws.Copy after:=newWb.Sheets(newWb.Sheets.Count)
        Application.DisplayAlerts = False ' 禁用确认删除的弹窗
        newWb.Worksheets(1).Delete
        'Application.DisplayAlerts = True
        
        Set newWs = newWb.Sheets(newWb.Sheets.Count)
        
        fileName = newWs.Name & ".csv"
        With newWs
            filePermissionCandidates = Array(savePath & fileName)
            fileAccessGranted = GrantAccessToMultipleFiles(filePermissionCandidates)
            If Not fileAccessGranted Then
                MsgBox savePath & ",授权失败"
                Exit Sub
            End If
            .SaveAs fileName:=savePath & fileName, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
            .SaveAs fileName:=savePath & fileName, FileFormat:=xlCSVUTF8, CreateBackup:=False
        End With
    Next ws
    newWb.Close SaveChanges:=False
    Set newWb = Nothing
    Set newWs = Nothing
End Sub

  

posted on 2024-05-26 13:18  孤山独剑  阅读(99)  评论(0编辑  收藏  举报

导航