我正在尝试获取最后使用的工作请求编号以填写序列中的下一个数字。我已经包含了Excel对象库。我在第二个for循环开始时遇到类型不匹配错误,但是当我在Excel中运行相同的代码时,它可以根据需要工作。代码段如下:
Sub GetDRNum()
Application.DisplayAlerts = False
Dim xl as Excel.Application, Wb As Excel.Workbook, I As integer
Dim ReqNum As String, lr As long, c As Range, lastReqNum As Long,
nextReqNum As String, rngStr As String
Set xl = CreateObject("Excel.Application")
Set Wb = xl.Workbooks.Open("K:\Desktop\IT Projects\IT Help Request\LTO-IT DR Log(revised).xlsm")
For i = 1 To Wb.Sheets.Count
With Wb.Sheets(i)
If .Name = "Validation" Then
'skip validation worksheet
GoTo myNext
ElseIf .Name = "Submitted" Then
rngStr = "B6:B"
ElseIf .Name = "Completed Requests" Then
rngStr = "B4:B"
End If
lr = .Cells(Rows.Count, 2).End(xlUp).Row
For Each c in WB.Sheets(i).Range(rngStr & lr)
If IsEmpty(c) Then
Exit For
ElseIf CLng(Right(Trim(c), 4)) > lastReqNum Then
lastReqNum = CLng(Right(Trim(c), 4))
End If
Next c
End With
myNext:
Next i
答案 0 :(得分:0)
原因是Word has a Range object也是{将其视为一系列文字)。
您需要像定义Excel App一样定义Excel范围。
Dim c As Excel.Range
请注意,只有登录用户的Word应用程序手动添加Excel对象引用时,此Word宏才能生效。
即。如果将其带到另一台计算机,则默认情况下不起作用。因此,如果您想要可移植性,我建议您使用Late Binding - 将它们全部与Excel As Object
相关联。