VBA Excel-将用户窗体文本框值添加到工作表

时间:2018-11-10 09:39:22

标签: excel vba excel-vba userform bookmarks

Private Sub Submit_Click()

'----------The Script below writes values to Word Doc ----------------------------------------

Dim wApp As Object
Dim wDoc As Object

'We need to continue through errors since if Word isn't
'open the GetObject line will give an error

'On Error Resume Next
Set wApp = GetObject(, "Word.Application")


'We've tried to get Word but if it's nothing then it isn't open
If wApp Is Nothing Then
    Set wApp = CreateObject("Word.Application")
End If

'It's good practice to reset error warnings
On Error GoTo 0

'Open your document and ensure its visible and activate after opening

Set wDoc = wApp.Documents.Open(Filename:="C:\Documents\example.docx ", ReadOnly:=False)
    With wDoc
    .Bookmarks("bookmark1").Range.Text = Me.TextBox1.Value 'how do I also insert the TextBox1.Value to the next empty row in worksheet?

'so far I got this to do it but everytime i click submit it puts it in the same cell instead of the next row

Sheet6.Range("H2").Value = Me.TextBox6.Value

    End With

wApp.Visible = True

'set default file name and file path

ProposedFileName = Format(Now(), "DDMMMYYYY") & TextBox1.Value & "-" & ".doc"
ProposedFilePath = "C:\Documents\"

    With wApp.FileDialog(msoFileDialogSaveAs)
    wDoc.SaveAs2 ProposedFilePath & ProposedFileName, _
    FilterIndex = 1, _
    FileFormat:=wdFormatDocument

End With
End Sub

大家好,

上面的代码只是我的脚本的一部分,当将用户窗体文本框值插入到Word doc中的bookmark1中时,它可以正常工作,但是例如,如何将这个文本框值也插入工作表行中,例如在列标题“名称”下?

谢谢。

1 个答案:

答案 0 :(得分:0)

我终于设法通过添加代码来解决了

Dim LastRow As Long, ws As Worksheet

Set ws = Sheets(2)

LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Finds the last blank row

ws.Range("A" & LastRow).Value = TextBox1.Value 'Adds the TextBox1 into Col A & Last Blank Row