我认为我找不到合适的术语,因为我想这个答案一定存在,但是我是函数的新手,并试图弄清楚如何使它起作用:
如何在我说findLastRow
的地方使用我的函数Range("B2" & findLastRow).Select
?我收到的当前错误是不可选参数,它突出显示了findLastRow
Public Function findLastRow(col As String) As Long 'making the macro available to all Sub Procedures
Dim lastRow As Long
With ActiveSheet
lastRow = ActiveSheet.Cells(1048576, col).End(xlUp).Row 'finding the last possible row disregarding blanks
End With
findLastRow = lastRow
End Function
Sub Open_INV()
ChDir "C:\Users\MonthEnd_Close\Import_Files"
Workbooks.OpenText Filename:= _
"C:\Users\MonthEnd_Close\Import_Files\INV", _
Origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False _
, Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
TrailingMinusNumbers:=True
On Error Resume Next
Range("B2").Formula = "=TRIM(A2)"
Range("B2").Copy
Range("B2:B" & findLastRow).Select
Selection.PasteSpecial xlPasteFormulas
End Sub
答案 0 :(得分:1)
请勿在函数中使用ActiveSheet。您将有一个绝佳的机会来传递具有已定义的父工作表的范围,而不是代表列字母的字符串。
Public Function findLastRow(col As range) As Long 'making the macro available to all Sub Procedures
Dim lastRow As Long
With col.parent
lastRow = .Cells(.rows.count, col.column).End(xlUp).Row 'finding the last possible row disregarding blanks
End With
findLastRow = lastRow
End Function
Sub Open_INV()
Workbooks.OpenText Filename:= _
"C:\Users\MonthEnd_Close\Import_Files\INV", _
Origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False _
, Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
TrailingMinusNumbers:=True
with activeworkbook.worksheets(1)
.Range("B2:B" & findLastRow(.range("A2"))).Formula = "=TRIM(A2)"
end with
End Sub