我的userform中有一个文本字段,其名称与没有空格的标签标题相同。例如,文本框将命名为“SampleName”,标签标题将为“Sample Name”。按下提交时,我希望将数据输入到工作簿中与名称和文本字段名称相同的相应列下。我无法从列标题中删除空格,因为导入到另一个软件需要空间。但是,当我点击提交时,它总是返回运行时错误,无法获得匹配属性。当我手动键入Label.ctlname.Caption尝试此代码时,它工作正常。有什么建议吗?
Dim ssheet As Worksheet
Dim rngsource As Range
Set ssheet = ThisWorkbook.Sheets("Sheet1")
nr = ssheet.Cells(Rows.Count, 1).End(xlUp).Row + 1
With ssheet
Set rngsource = Range(Cells(1, 1), Cells(1, Range("A1").End(xlToRight).Column))
Dim ctl
Dim ctlname As String
For Each ctl In Me.Controls
If TypeOf ctl Is msforms.TextBox Then
ctlname = "Label" & ctl.Name & ".Caption"
.Cells(nr, Application.WorksheetFunction.Match(ctlname, rngsoruce, 0)) = ctl
ctl.Text = ""
End If
Next ctl
End With
答案 0 :(得分:0)
我建议:
Labels
此过程遵循上面定义的步骤,并在工作表中提供字段名称的可能格式,使用所需格式并注释\删除其他格式。
Sub UserForm_PostToWsh()
Dim ws As Worksheet, rgSrc As Range
Dim oCtrl As Object, MsfTb As MSForms.TextBox
Dim sFld As String, lRow As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lRow = 1 + .Cells(.Rows.Count, 1).End(xlUp).Row
Set rgSrc = .Cells(1).Resize(1, .Cells(1).End(xlToRight).Column)
For Each oCtrl In UfrNew_01.Controls
Rem Validate Control as Label
If TypeOf oCtrl Is MSForms.Label Then
Rem Set Associated TextBox
Set MsfTb = Nothing
On Error Resume Next
Set MsfTb = UfrNew_01.Controls(Replace(oCtrl.Name, "Label", vbNullString))
On Error GoTo 0
Rem Validate TexBox
If Not MsfTb Is Nothing Then
sFld = oCtrl.Name & "." & oCtrl.Caption 'If Field format is LabelName.LabelCaption use this line
'sFld = oCtrl.Name & "." & MsfTb.Name 'If Field format is LabelName.TextBoxName use this line
'sFld = oCtrl.Caption & "." & oCtrl.Name 'If Field format is LabelCaption.LabelName use this line
'sFld = oCtrl.Caption & "." & MsfTb.Name 'If Field format is LabelCaption.TextBoxName use this line
'sFld = MsfTb.Name & "." & oCtrl.Name 'If Field format is TextBoxName.LabelName use this line
'sFld = MsfTb.Name & "." & oCtrl.Caption 'If Field format is TextBoxName.LabelCaption use this line
Rem Post Text Value
.Cells(lRow, WorksheetFunction.Match(sFld, rgSrc, 0)) = MsfTb.Value
Rem Initialize TextBox
MsfTb.Text = vbNullString
End If: End If: Next: End With
End Sub