簡體   English   中英

Excel VBA無法獲取WorksheetFunction類的Match屬性

[英]Excel VBA unable to get the Match property of the WorksheetFunction class

我的用戶窗體中有一個文本字段,名稱與標簽標題相同,但沒有空格。 例如,文本框將被命名為“ SampleName”,標簽標題將被命名為“ Sample Name”。 當按下提交時,我希望將數據輸入到工作簿中與標題和文本字段名稱相同的相應列下。 我無法從列標題中刪除該空間,因為該空間是導入另一個軟件所必需的。 但是,當我點擊Submit時,它總是返回無法獲取match屬性的運行時錯誤。 當我在手動鍵入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

我建議:

  1. 識別用戶表單中的Labels
  2. 將關聯的文本框設置為標簽
  3. 建立字段名稱並獲取“字段”列
  4. 將TextBox值發布到相應的字段列中
  5. 清除文字框

此過程按照上面定義的步驟進行,並提供工作表中字段名稱的可能格式,使用所需的格式,並注釋\\刪除其他格式。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM