Private Sub CommandButton1_Click()
Dim wsIndex As Worksheet
Dim nextRow As Long
' 設定工作表
Set wsIndex = ThisWorkbook.Sheets("圖號建立索引")
' 獲取下一行,從B列開始
nextRow = wsIndex.Cells(wsIndex.Rows.Count, "B").End(xlUp).Row + 1
' 將 TextBox2、TextBox4、TextBox5 的內容寫入圖號建立索引的相應列
wsIndex.Cells(nextRow, "A").Value = TextBox6.Value ' 將 TextBox2 的值填入 A 列
wsIndex.Cells(nextRow, "B").Value = TextBox2.Value ' 將 TextBox2 的值填入 B 列
wsIndex.Cells(nextRow, "C").Value = TextBox4.Value ' 將 TextBox4 的值填入 C 列
wsIndex.Cells(nextRow, "D").Value = TextBox5.Value ' 將 TextBox5 的值填入 D 列
' 設定內容靠左對齊
wsIndex.Cells(nextRow, "A").HorizontalAlignment = xlLeft
wsIndex.Cells(nextRow, "B").HorizontalAlignment = xlLeft
wsIndex.Cells(nextRow, "C").HorizontalAlignment = xlLeft
wsIndex.Cells(nextRow, "D").HorizontalAlignment = xlLeft
' 可以選擇清空 TextBox,以便於下一次輸入
TextBox2.Value = ""
TextBox4.Value = ""
TextBox5.Value = ""
' 顯示提示訊息,確認成功
MsgBox "資料已成功添加到圖號建立索引!", vbInformation
End Sub
Private Sub CommandButton2_Click()
' 清空所有指定的 TextBox
TextBox2.Value = ""
TextBox4.Value = ""
TextBox5.Value = ""
' 可選:如果需要,也可以清空 ComboBox 和其他 Input 控件
ComboBox1.Value = ""
TextBox3.Value = ""
' 提示用戶內容已被清空
MsgBox "所有內容已被清除!", vbInformation
End Sub
Private Sub CommandButton3_Click()
' 將ψ追加到 TextBox4 中,不移除之前的內容
TextBox4.Value = TextBox4.Value & "ψ"
End Sub
Private Sub Label3_Click()
End Sub
Private Sub Label4_Click()
End Sub
Private Sub TextBox3_Change()
End Sub
Private Sub TextBox6_Enter()
TextBox6.Value = Format(Date, "yyyy-mm-dd") ' 設定顯示的日期格式
End Sub
Private Sub UserForm_Initialize()
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
TextBox6.Value = Format(Date, "yyyy/mm/dd") ' 設定顯示的日期格式
' 設定工作表以讀取類別清單
Set ws = ThisWorkbook.Sheets("類別清單")
Set rng = ws.Range("C2:C999") ' 讀取 C2:C999 的範圍
' 清空 ComboBox 以防重複填充
ComboBox1.Clear
' 將範圍中的每一個單元格的值添加到 ComboBox
For Each cell In rng
If Not IsEmpty(cell.Value) Then
ComboBox1.AddItem cell.Value
End If
Next cell
End Sub
Private Sub ComboBox1_Change()
Dim ws As Worksheet
Dim wsIndex As Worksheet
Dim matchRow As Variant
Dim newSerial As Long
Dim yearSuffix As String
Dim prefix As String
Dim currentNumber As Long
Dim baseValue As String
' 設定工作表
Set ws = ThisWorkbook.Sheets("類別清單")
Set wsIndex = ThisWorkbook.Sheets("圖號建立索引")
' 根據 ComboBox1 的選擇,更新 TextBox3
matchRow = Application.Match(ComboBox1.Value, ws.Range("C2:C999"), 0)
If Not IsError(matchRow) Then
TextBox3.Value = ws.Cells(matchRow + 1, "B").Value ' +1 因為 Match 返回的是 1 基數
Else
TextBox3.Value = ""
End If
' 取得當前年份後兩碼
yearSuffix = Right(Year(Date), 2)
' 初始化流水號
newSerial = 1
' 檢查生成的字符串是否存在於圖號建立索引的B列中
Do
baseValue = TextBox3.Value & "-" & yearSuffix & Format(newSerial, "000") ' 更新 baseValue
If Not IsError(Application.Match(baseValue, wsIndex.Range("B:B"), 0)) Then
newSerial = newSerial + 1 ' 如果重複,流水號加1
End If
Loop While Not IsError(Application.Match(baseValue, wsIndex.Range("B:B"), 0))
' 最終更新 TextBox2 的值
TextBox2.Value = baseValue ' 這將是唯一的值
End Sub
請加入我的程式裡面