我尝试在outlook中编写VBA脚本以增加excel中的单元格行。但是我不能为这个变量设置默认值(我使用公共变量,单元格行应该从“2”开始)。
如何在outlook中使用脚本VBA在第一次在excel中设置第二行单元格(单元格(2,1)= 1),并在下次增加单元格行
这是我在outlook中的代码。当我运行它时,它说“无效的外部程序”
Public count As Integer: count = 2
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
'Check file open or not, and open it if it isn't opened
If (IsWorkBookOpen("D:\Book1.xlsx") = True) Then
Set xlWB = xlApp.Workbooks("Book1.xlsx")
Else
Set xlWB = xlApp.Workbooks.Open("D:\Book1.xlsx")
End If
Set xlSheet = xlWB.Sheets("Sheet1")
'Process excel file
xlSheet.Cells(count, 1) = 1
count = count + 1
End Sub
Function IsWorkBookOpen(FileName As String) 'function to check excel file is open or not
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
答案 0 :(得分:0)
在VBA中,您无法将值分配给子例程之外的非常量。
Public count As Integer: count = 2
您可以使用Workbook_Open()
事件初始化您的公共变量。
Private Sub Workbook_Open()
counter = 2
End Sub
或者,您可以使用GetSettings
和SaveSetting
参考:MSDN GetSetting Function
答案 1 :(得分:0)
使用Static
变量在同一Outlook会话的不同运行之间保留其值
Sub test()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Static count As Integer '<-- 'Static' preserves values between consecutive runs
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Set xlApp = CreateObject("Excel.Application")
End If
On Error GoTo 0
'Check file open or not, and open it if it isn't opened
If IsWorkBookOpen("D:\Book1.xlsx") Then
Set xlWB = xlApp.workbooks("Book1.xlsx") '<-- 'workbooks()' acctepts only file name and extension
Else
Set xlWB = xlApp.workbooks.Open("D:\Book1.xlsx")
End If
Set xlSheet = xlWB.Sheets("Sheet1")
If count = 0 Then count = 2 '<-- 1st time it sets count to 2
xlSheet.Cells(count, 1) = 1
count = count + 1 '<-- increment count for next time to be left as it is before writing to xlSheet
End Sub