如果条件满足,我想保存我的文件。我已经写了下面的代码,但它不起作用

时间:2018-10-30 10:16:55

标签: excel vba excel-vba

在这里,我想比较三个值,如果三个值相等,则仅应将其另存为文件。

Sub test()


    m = 1
    n = 1
    b = 5


    If m = n = b Then Sheet1.Activate

    Sheet1.Copy

    MsgBox "This new workbook will be saved as MyWb.xls(x)"

    'Save new workbook as MyWb.xls(x) into the folder where ThisWorkbook is stored
    ActiveWorkbook.SaveAs ThisWorkbook.Path & "\MNP", xlWorkbookNormal
    MsgBox "It is saved as " & ActiveWorkbook.FullName & vbLf & "Press OK to close it"

    ' Close the saved copy
    ActiveWorkbook.Close False




    End Sub

2 个答案:

答案 0 :(得分:1)

一种选择:

要比较If语句中的数据,您需要添加逻辑运算符。如果您想说m = nb = a,就一样。 So add AND in this case

应用If时,还需要以End If结尾

Sub tsat()

Dim m As Long
Dim n As Long
Dim b As Long


m = 1
n = 1
b = 1


If (m = n And m = b) Then

Sheet1.Activate

Sheet1.Copy

MsgBox "This new workbook will be saved as MyWb.xls(x)"

'Save new workbook as MyWb.xls(x) into the folder where ThisWorkbook is stored
ActiveWorkbook.SaveAs ThisWorkbook.Path & "\MNP", xlWorkbookNormal
MsgBox "It is saved as " & ActiveWorkbook.FullName & vbLf & "Press OK to close it"

' Close the saved copy
ActiveWorkbook.Close False

Else

MsgBox "Values are not equal. " & " m=" & m & ", n=" & n & ", b=" & b

End If
End Sub

答案 1 :(得分:-1)

我不确定您要做什么-但是如果您想将工作表1另存为其他名称,那么

Sub Demo

Dim m,n,b
If application.worksheetfunction.And(m=n,m=b) then
    dim wbTarget as workbook
    set wbtarget = workbooks.add()
    ThisWorkbook.Sheets(1).copy before:=wbtarget.sheets(1)
    wbTarget.saveas ThisWorkbook.Path & "\MNP.xlsx"
    wbtarget.close
    msgbox "Sheet 1 has been saved as MNP.xlsx"
end if
end Sub