欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Excel VBA 中 Excel文件的操作

程序员文章站 2022-05-14 23:47:15
...
'1 判断A.Xls文件是否存在
    Sub W1()
     If Len(Dir("D:\A.xls")) = 0 Then
       MsgBox "A文件不存在"
     Else
       MsgBox "A文件存在"
     End If
   End Sub

'2 判断A.Xls文件是否打开
    Sub W2()
     Dim X As Integer
      For X = 1 To Windows.Count
        If Windows(X).Caption = "A.xls" Then
          MsgBox "A文件打开了"
          Exit Sub
        End If
      Next
    End Sub

'3 excel文件新建和保存

  Sub W3()
     Dim wb As Workbook
     Set wb = Workbooks.Add
       wb.Sheets("sheet1").Range("a1") = "zch19960629"
     wb.SaveAs "D:\B.xls"
  End Sub

'4 excel文件打开和关闭

 Sub w4()
    Dim wb As Workbook
    Set wb = Workbooks.Open("D:\B.xls")
    MsgBox wb.Sheets("sheet1").Range("a1").Value
    wb.Close False
 End Sub

'5 excel文件保存和备份
   Sub w5()
      Dim wb As Workbook
      Set wb = ThisWorkbook
      wb.Save
      wb.SaveCopyAs "D:\ABC.xls"
   End Sub

'6 excel文件复制和删除
   Sub W6()
      FileCopy "D:\B.xls", "D:\ABCd.xls"
      Kill "D:\ABC.xls"
      MsgBox ("删除完成")
   End Sub

VBA打开已有的Word文档:

方法一:

Public Sub OpenWord ()
    Dim myFile As String
    Dim docApp As Word.Application
    '指定要打开的Word文档
    myFile = ThisWorkbook.Path & "\VBA打开Word文档.docx"
    Set docApp = New Word.Application
    With docApp
        .Documents.Open myFile
        .Visible = True
    End With
    Set docApp = Nothing
End Sub

方法二:


Public Sub OpenWord2()
    Dim myFile As String
    Dim docApp As Object
    '指定要打开的Word文档
    myFile = ThisWorkbook.Path & "\VBA打开Word文档.docx"
    Set docApp = CreateObject("Word.Application")
    With docApp
        .Documents.Open myFile
        .Visible = True
    End With
    Set docApp = Nothing
End Sub