iT邦幫忙

0

EXCEL 記錄亂數在另一個工作表

小弟目前遇到一個問題想請教一下

我設計了一個亂數A1~A10,然後從中選一個最大值紀錄在C9這裡,上方的按鈕是重洗亂數
https://ithelp.ithome.com.tw/upload/images/20210121/20134574fTNVpMHGRW.png

然後我希望按第1次按鈕就把結果記錄在工作表2的B1,按第2次按紐就記錄在工作表2的B2以此類推...
https://ithelp.ithome.com.tw/upload/images/20210121/20134574kgLipf5TJC.png

但就發現怎麼樣都沒辦法達成這樣的效果,工作表2的B欄公式都是"=工作表1!C9"
結果一按鈕整欄的數字都一起改了...

請問這個要怎麼解決?

微笑 iT邦新手 1 級 ‧ 2021-01-21 15:43:43 檢舉
不要用函數,取最大值寫入的方法一起寫進button
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
1
rogeryao
iT邦超人 8 級 ‧ 2021-01-21 17:34:20
最佳解答
Private Sub CommandButton1_Click()
Randomize

Dim Y As Integer
'Y:要執行的次數
Y = 5
If Worksheets("工作表2").Cells(Y, 2) = "" Then
  '產生 10 個亂數
  For M = 1 To 10
    Worksheets("工作表1").Cells(M, 1) = Rnd
  Next M
  
  For X = 1 To Y
    If Worksheets("工作表2").Cells(X, 2) = "" Then
      Worksheets("工作表2").Cells(X, 1) = "第 " & X & " 次"
      Worksheets("工作表2").Cells(X, 2) = [max(工作表1!A1:A10)]
      Exit For
    End If
  Next X
Else
  MsgBox "已經執行 " & Y & " 次了," & "若要重新執行,請先清空工作表2的B欄位."
End If

End Sub
0
微笑
iT邦新手 1 級 ‧ 2021-01-21 16:42:26

google sheets上不能用VBA,你下載開看看是不是你要的

https://drive.google.com/file/d/1VlX6siq7TCcrqayeIek16Kaxxz52akXI/view?usp=sharing

程序部份

Sub testDo()
 '關閉自動更新
 Excel.Application.Calculation = xlCalculationManual
 
 '手動更新
 Calculate
 
 '儲存資料
 Dim data(4) As String
 
 data(0) = Cells(2, 6)
 data(1) = Cells(2, 7)
 data(2) = Cells(2, 8)
 data(3) = Cells(2, 9)
 
 '找空格塞結果
 For i = 0 To 3
    If (data(i) = "") Then
        Cells(2, 6 + i) = Range("C12")
        i = 4
    End If
 Next
 
 '開啟自動更新
 'Excel.Application.Calculation = xlCalculationAutomatic
End Sub
0
shock168
iT邦新手 5 級 ‧ 2021-01-24 07:01:45

工作表 1 設如下: (原 Formula 不變動)
1.將 Excel "公式" -> "重算選項" 設為 "手動"
2.將 "C9" 命名為"最大值"
3.增加 ActiveX CommandButton 於其上,並命名為 "btnFlush"
4.工作表 1 物件寫入:

Private Sub btnFlush_Click()
    Dim iLastPos As Integer
       
    On Error Resume Next
    iLastPos = Worksheets("工作表2").Columns(2).SpecialCells(xlCellTypeConstants).Count
    On Error GoTo 0
    
    If iLastPos <= 4 Then
        Application.Calculate
        Worksheets("工作表2").Range("B1").Offset(iLastPos).Value = Worksheets("工作表1").Range("最大值").Value
    Else
        If MsgBox("紀錄已滿!" & vbCrLf & "是否要重新記錄? (Y/N)", vbExclamation + vbYesNo, "注意") = vbYes Then
            Worksheets("工作表2").Columns(2).SpecialCells(xlCellTypeConstants).Delete xlShiftUp
            MsgBox "紀錄全部已清空!", vbExclamation + vbOKOnly, "注意"
        End If
    End If
End Sub

我要發表回答

立即登入回答