I have a question about using a private function inside a private sub (command button).
It doesn't return any errors... nor does it do anything. When I press the command button in Word doc, it is supposed to form rows and import data from an Excel worksheet until the last row in Excel, which is what I'm trying to get the function to do - find the last row in the worksheet.
If you can look at my code and let me know if you know why it won't work, I'd appreciate it. Do I need to have the function inside the Private Sub commandbutton_2_Click()? Thank you in advance.
Private Sub CommandButton2_Click()
Dim tbl As Table
Dim row As row
Set tbl = ActiveDocument.Tables(2)
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
On Error Resume Next
Set exWb = objExcel.Workbooks.Open("S:\Electro-Protocol\Mot_Protocols\" & TextBox1 & ".xls")
Dim lastRow As Integer
lastRow = GetLastRow(objExcel, exWb)
ActiveDocument.Tables(2).Columns.DistributeWidth
For counter = 1 To lastRow
tbl.Rows.Add
tbl.cell(counter, 1).Range.Text = exWb.Sheets("Tabelle1").Cells(counter, 1)
tbl.cell(counter, 2).Range.Text = exWb.Sheets("Tabelle1").Cells(counter, 2)
tbl.cell(counter, 3).Range.Text = exWb.Sheets("Tabelle1").Cells(counter, 3)
tbl.cell(counter, 4).Range.Text = exWb.Sheets("Tabelle1").Cells(counter, 4)
tbl.cell(counter, 5).Range.Text = exWb.Sheets("Tabelle1").Cells(counter, 5)
tbl.cell(counter, 6).Range.Text = exWb.Sheets("Tabelle1").Cells(counter, 6)
Next counter
End Sub
Private Function GetLastRow(ByVal objExcel As Excel.Application, ByVal exWb As Excel.Workbook) As Integer
Dim lastRow As Integer
lastRow = 0
With exWb.Sheets("Tabelle1")
If objExcel.WorksheetFunction.CountA(.Cells) <> 0 Then
lastRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).row
Else
lastRow = 1
End If
End With
End Function
On Error Resume Next. It won't show you any errors if that command is in your code