SaveAs不会接受包含"。"的字符串。在Excel VBA中

时间:2016-03-30 22:05:46

标签: excel vba excel-vba

我使用以下代码添加新工作簿,保存并命名工作簿(基于位于工作表中某个单元格中的日期)。

Dim wb As Workbook
Dim wbName As String
wbName = ThisWorkbook.Sheets("Sheet1").Range("M145").value 


    fName = Application.GetSaveAsFilename(wbName)
    If fName = False Then
        MsgBox "Publish couldn't be completed since you didn't choose where to save the file."
        Exit Sub
    Else
        Set wb = Workbooks.Add
        wb.SaveAs (fName)
    End If

但似乎每当细胞" M145"包含点("。"),如" 31.3.16",我的文件名不会出现在SaveAs提示中,我看到一个空白行没有 任何错误信息。

我不认为这与它有任何关系,但我的表格从右到左。有没有人知道如何解决这个问题?

2 个答案:

答案 0 :(得分:6)

虽然我无法复制错误,但也许你会对FileDialog对象有更好的运气:

Dim wb As Workbook
Dim wbName As String
Dim fdlg As FileDialog

wbName = ThisWorkbook.Sheets("Sheet1").Range("M145").value 

Set fdlg = Application.FileDialog(msoFileDialogSaveAs)
With fdlg
    .InitialFileName = wbName
    .Show
    Set wb = Workbooks.Add
    On Error Resume Next 'Suppress any errors due to invalid filename, etc.
    wb.SaveAs(fdlg.SelectedItems(1))
    If Err.Number <> 0 Then  
        MsgBox "Publish couldn't be completed since you didn't choose where to save the file."
        wb.Close False  'Get rid of the workbook since it's not being saved
        Exit Sub
    End If
    On Error GoTo 0 'Resume normal error handling
End With

答案 1 :(得分:2)

这里有两件事。

首先,M145可能包含格式掩码为dd\.mm\.yy的日期。要将显示的值从单元格中移出并变为变量,您需要Range.Text property,而不是Range.Value property

其次,Application.GetSaveAsFilename method的默认文件类型为*.*,这意味着它将接受.yy作为文件扩展名。您需要将可用的文件扩展名限制为Excel文件类型。

Dim wb As Workbook
Dim wbName As String, fName As Variant  'variant in case user clicks Cancel

wbName = ThisWorkbook.Sheets("Sheet1").Range("M145").Text

With Application
    fName = .GetSaveAsFilename(InitialFileName:=wbName, _
                               FileFilter:="Excel Workbook (*.xlsx), *.xlsx," & _
                                           "Macro Workbook (*.xlsm), *.xlsm," & _
                                           "Binary Workbook (*.xlsb), *.xlsb")
End With

这可以帮助您解决文件名选择问题。但是,Workbook.SaveAs method也应该提供正确的XlFileFormat Enumeration

Select Case fName
    Case False
        'user clicked Cancel or Close (×)
        Debug.Print fName
    Case Else
        With Workbooks.Add
            Select Case Right(fName, 5)
                Case ".xlsx"
                    .SaveAs Filename:=fName, FileFormat:=xlOpenXMLWorkbook
                Case ".xlsm"
                    .SaveAs Filename:=fName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
                Case ".xlsb"
                    .SaveAs Filename:=fName, FileFormat:=xlExcel12
                Case Else
                    'there really shouldn't be a case else
            End Select
        End With
End Select