Excel Personal.xlsb保存文档宏

时间:2016-10-04 18:50:20

标签: excel vba excel-vba macros

我有一个宏来查看一个单元格是否包含这个字符串,如果这样就执行"另存为"具有此设置名称标准的命令。当我尝试运行宏时,if语句似乎不起作用。当我逐步完成它命中if语句但保存personal.xlsb而不是我正在处理的文件。这里的代码我知道我有什么问题

Dim FName           As String
Dim FPath           As String
Dim answer          As Integer
If ActiveWorkbook.Sheets("Sheet1").Range("A1") = "String1" Then
    FPath = "C:\String1"
    FName = Sheets("Sheet1").Range("A1").Text
    If Len(FPath & "\" & FName) = 0 Then 
        answer = MsgBox("Do you want to Save File As: " & FName & "?", vbYesNo + vbQuestion, "Microsoft Excel")
        If answer = vbYes Then
            ThisWorkbook.SaveAs Filename:=FPath & "\" & FName
        End If
    Else
        ThisWorkbook.Save
    End If
End If

我愿意接受建议,我最多的是检查文件是否包含字符串,如果是,则验证它是否已经存在,如果是,则只保存而不是另存为。

1 个答案:

答案 0 :(得分:1)

ThisWorkbook指的是代码所在的工作簿。据推测,代码在Personal.xlsb中,这就是为什么它保存XLSB文件而不是活动工作簿。

请改为尝试:

Dim FName           As String
Dim FPath           As String
Dim fullName As String
Dim rng As Range
Dim s as String
s = "String1"
With ActiveWorkbook
    Set rng = .Sheets("Sheet1").Range("A1")
    If rng.Value = s Then
        FPath = "C:\" & s
        FName = rng.Text
        fullName = FPath & "\" & FName
        If Len(fullName) = 0 Then 
            If MsgBox("Do you want to Save File As: " & FName & "?", vbYesNo + vbQuestion, "Microsoft Excel") = vbYes Then
                .SaveAs Filename:=fullName
            End If
        Else
            .Save
        End If
    End If
End With