我正在尝试创建一个用户表单,以逻辑方式将数据插入电子表格的最后一行,但是一旦我将数据放入单元格中,数据就不会被格式化。我的第一个想法是在删除数据之前简单地选择最后一行并格式化它。'。Row.Autofit'属性适用于此代码,但其他设置,例如左对齐的文本,这是什么我真的需要,不要工作。我错过了什么? (出于NDA原因,我用“Stuff”替换了所有用户表单文本内容和变量。我知道这会创建重复项)
Private Sub StuffUpload_Click()
Dim ws As Worksheet
' Grabs the worksheet that the user is currently looking at, making this
' form work on all sheets
Set ws = ActiveSheet
' Make sure all required fields have been entered
If Stuff.Text = "" Then
MsgBox "You must enter Stuff."
Stuff.SetFocus
Exit Sub
End If
' Add a dash of formatting to the last row so the stuff we put into it will
' look nice
ws.Range("B" & Rows.Count).End(xlUp).Offset(1).Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Rows.AutoFit
End With
' Adds the Stuff info into Col B at the Last Blank Row
ws.Range("B" & Rows.Count).End(xlUp).Offset(1).Value = Me.Stuff.Value
' Add date and time stamp for the moment the comment was entered
ws.Range("C" & Rows.Count).End(xlUp).Offset(1).Value = Date + Time
' Adds the Stuff info into Col D at the last Blank Row
ws.Range("D" & Rows.Count).End(xlUp).Offset(1).Value = Me.Stuff.Value
Unload Me
End Sub
答案 0 :(得分:1)
尝试使用以下代码替换您的代码:
Private Sub StuffUpload_Click()
Dim ws As Worksheet
Dim LastRow As Long
Dim RngAnchor As Range
' Grabs the worksheet that the user is currently looking at,
' making this form work on all sheets
Set ws = ActiveSheet
' Make sure all required fields have been entered
If Stuff.Text = "" Then
MsgBox "You must enter Stuff."
Stuff.SetFocus
Exit Sub
End If
' Add a dash of formatting to the last row so the stuff we put into it will
' look nice
With ws
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row ' get the last row in column "B"
' set the anchor point of the range in column "B"
Set RngAnchor = .Range("B" & LastRow + 1)
' Adds the Stuff info into Col B at the Last Blank Row
RngAnchor.Value = Me.Stuff.Value
' Add date and time stamp for the moment the comment was entered
RngAnchor.Offset(, 1).Value = Now
' Adds the Stuff info into Col D at the last Blank Row
RngAnchor.Offset(, 2).Value = Me.Stuff.Value '<-- already added this on Column "B"
' now format last row, cells "B:D"
With RngAnchor.Resize(1, 3)
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Rows.AutoFit
End With
End With
Unload Me
End Sub