簡體   English   中英

更改VBA代碼以從定義的單元格而不是文本框中讀取(Excel)

[英]Changing a VBA code to read from a defined cell instead of a text box (Excel)

我搜索了該站點,並從此處找到了一個用戶的代碼,該代碼幾乎適合我的應用程序。

Private Sub TextBox1_Change()
    If InStr(2, TextBox1, "*RCBC*") > 1 Then
        Me.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = Me.TextBox1.Value
        Me.TextBox1.Text = ""
    End If
End Sub

一旦找到RCBC,此代碼將采用在文本框中輸入的數據並將其移至A列中的第一個可用位置。

我要更改的是,此代碼從定義的單元格而不是文本框中執行此任務。 由於此應用程序是從條形碼掃描儀接收數據,並在找到該字符串時移動內容。 掃描程序只會將數據輸入到單元中。 我對VBA知之甚少,但有一定的編碼背景。

先感謝您。

您將在與TextBox1_Change相同的私有工作表代碼表中需要一個worksheet_change事件子過程。

sub worksheet_change(byval target as range)
    if not intersect(target, range("B1")) is nothing then
        on error goto safe_exit
        application.enableevents = false
        If InStr(2, range("B1").Value, "RCBC") > 1 Then
            Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = range("B1").Value
            range("B1") = vbnullstring
        End If
    end if
safe_exit:
    application.enableevents = true
end sub

Worksheet_Change()是一個事件,您可以使用:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False

    If Target.Cells.Count > 1 Then Exit Sub
    If InStr(2, UCase(Target.Value2), "RCBC") > 1 Then
        Target.Value2 = Target.Value2
    Else
        Target = vbNullString
    End If

    Application.EnableEvents = True

End Sub
  • 添加了UCase() ,因此它也檢查RCbCRcBc
  • 需要Application.EnableEvents = False來臨時禁用事件,從而避免循環不斷,因為在同一單元中一遍又一遍地寫。
  • Target.Cells.Count > 1檢查所選單元格的數量。

暫無
暫無

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

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