我正在努力找出如何在word中循环excel中的所有行。我想要实现的是,如果excel中的WP列中有某些内容,则使用该文件名保存活动的worddocument。但是我无法弄清楚最后一行(可能是中间的空行)之类的东西,我只是得到错误代码424,根据MSDN没有给我任何真正的提示什么是错的。任何想法都错了吗?
Public Sub test()
Dim xlapp As Object
Set xlapp = CreateObject("Excel.Application")
myFileName = "Z:\Dokumentstyring\UnderArbeid\PARTSLIST.xlsm"
xlapp.Workbooks.Open myFileName
xlapp.Application.ScreenUpdating = False
xlapp.Visible = False
a = xlapp.sheets("List").Range("A1").Value
b = firstBlankRow(xlapp)
c = getColumn("WP", xlapp)
xlapp.Application.ScreenUpdating = True
xlapp.ActiveWorkbook.Close (True)
xlapp.Quit
Set xlapp = Nothing
End Sub
我接收最后一行的功能:
Function firstBlankRow(ByRef xlapp) As Long
'returns the row # of the row after the last used row
'Or the first row with no data in it
With xlapp.sheets("List")
'~~> Check if there is any data in the sheet
'If xlapp.WorksheetFunction.CountA(.Cells) <> 0 Then
firstBlankRow = .Range("A" & .Rows.Count).End(Excel.XlDirection.xlUp).Row
'Else
firstBlankRow = 1
'End If
End With
End Function
这是我获取列号的功能
Public Function getColumn(header As String, ByRef xlapp) As Integer
Dim rng1 As Range
With xlapp.sheets("List")
Set rng1 = .Range(.Cells(1, 1), .Cells(1, Columns.Count)).Find(header, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
getColumn = rng1.Column
Else
MsgBox "Column " & header & " does not exist, Typo??", vbCritical
getColumn = -1
End If
End With
End Function
答案 0 :(得分:0)
根据评论中的对话,将Dim Rng1 As Range
更改为
Dim Rng1 As Object
。
您可以找到XlDirection,Xlvalues,xlwhole枚举的实际值。
最好这样做更好:
Private Const xlUp as long = -4162
'and so on
<强> EDIT1:强>
这是一个经过调整的功能,可以解决您的问题(我已经在我的机器上对其进行了测试)
Public Function getColumn(header As String, ByRef xlapp) As Long
Dim rng1 As Object
With xlapp.sheets("List")
Set rng1 = .Range(.Cells(1, 1), .Cells(1, .Columns.Count))
If rng1 Is Nothing Then
MsgBox ("ERROR: Range object is empty.")
getColumn = -1
Exit Function
End If
For Each m In rng1
If m = "WP" Then
getColumn = m.Column
Exit Function
End If
Next m
MsgBox "Column " & header & " does not exist, Typo??", vbCritical
getColumn = -1
End With
End Function