用于选择文件夹路径以在工作簿中保存多个电子表格的代码?

时间:2016-01-25 18:28:19

标签: excel vba excel-vba loops

我有一个包含多个电子表格的工作簿,我希望将它们保存为我选择的文件夹中的单个csv文件(保留其各自电子表格中的文件名)。

以下代码似乎让我选择了一个路径,但错误消息如下: 错误代码9 下线超出此行的范围     对于每个Ws In Sheets(数组(“01 - 货币”,“......,”14 - 用户定义的     字段“)) 我错过了什么?

Sub SaveOnlyCSVsThatAreNeeded()
Dim ws As Worksheet, newWb As Workbook
Dim pathh As Variant

Dim FolderName As String

With Application.FileDialog(msoFileDialogFolderPicker)
    .AllowMultiSelect = False
    If .Show = -1 Then
       FolderName = .SelectedItems(1)
    End If
End With

pathh = FolderName

Application.ScreenUpdating = False
For Each ws In Sheets(Array("01 - Currencies", "...., "14 - User Defined  
Fields"))

ws.Copy
Set newWb = ActiveWorkbook
With newWb
  .SaveAs pathh.path & "\" & ws.Name, xlCSV
  .Close (False)
End With
Next ws
Application.ScreenUpdating = True

End Sub

2 个答案:

答案 0 :(得分:1)

除了每个工作表的父工作簿之外,pathh.Path存在问题。 FolderName已经是所选文件夹的完整路径;你不需要找到它的.Path。这会产生:

  

运行时错误424:需要对象。

Sub SaveOnlyCSVsThatAreNeeded()
    Dim ws As Worksheet, wb As Workbook
    Dim pathh As Variant

    Set wb = ActiveWorkbook

    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        If .Show = -1 Then  'a folder was picked
           pathh = .SelectedItems(1)
        End If
    End With

    If pathh = False Then Exit Sub   'no folder picked; pathh is false

    Application.ScreenUpdating = False
    For Each ws In wb.Sheets(Array("Sheet1", "Sheet2", "Sheet4"))
        ws.Copy
        With ActiveWorkbook
            'Application.DisplayAlerts = False   'to avoid overwrite warnings
            '  pathh is a string (variant) of the path of the folder; does not need pathh.Path
            .SaveAs pathh & "\" & ws.Name, xlCSV
            .Close SaveChanges:=False
        End With
    Next ws

    Application.ScreenUpdating = True

End Sub

请勿忘记仔细检查数组中的工作表名称是否存在拼写错误。

答案 1 :(得分:0)

也许......

class Car {
    let Name : String
    let Mpg : Int
    let Price : Double
    init(name: String, mpg : Int, price : Double ) {
        Name = name
        Mpg = mpg
        Price = price
    }
}
...
private var carList = [Car]()
...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reusableCell", forIndexPath: indexPath) as! CustomCell
    Car car = carList[indexPath.row]
    cell.displayCarName!.text= car.Name
    cell.displayMpg!.text = String(car.Mpg)
    cell.displayCarPrice!.text = String(car.Price)
    return cell
}

或者

For Each ws In ActiveWorkbook.Worksheets