我想使用VBA从Outlook编辑Excel中的单元格。
我希望如此:
我第一次运行宏时,Cell A1是" 1"。
第二次运行宏时,Cell A2是" 1"
第三次运行宏时,Cell A3是" 1"
。
。
当我第五次运行宏时,它返回到单元格A1并从" 1"增加单元格A1的值。到" 2"。
Dim count As Integer: count = 1
Dim number As Integer: number = 1
Sub test()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Set xlApp = CreateObject("Excel.Application")
End If
On Error GoTo 0
If (IsWorkBookOpen("D:\Book1.xlsx") = True) Then 'Check workbook is opening or not
Set xlWB = xlApp.Workbooks("D:\Book1.xlsx")
Else
Set xlWB = xlApp.Workbooks.Open("D:\Book1.xlsx")
End If
Set xlSheet = xlWB.Sheets("Sheet1")
If (count < 5) Then
xlSheet.Range("A" & count) = number
count = count + 1
Else
count = 0
number = number + 1
End If
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
它说&#34;下标超出范围&#34;。我对此行有疑问:Set xlWB = xlApp.Workbooks("D:\Book1.xlsx")
。当我调试时,我看到这一行突出显示。
答案 0 :(得分:0)
这是因为使用Workbooks(...)
隐式使用Workbooks
对象的Item()
属性,该对象需要名称或对象的索引编号,而你是givin它是路径的全名
使用
Set xlWB = xlApp.workbooks("Book1.xlsx")