优化代码:Private Sub CommandButton1_ClickCall userinitDim i As IntegerDim namestr As String othername As StringDim lastRow As LongDim myValue As IntegerlastRow = CellsRowsCount AEndxlUpRowFor i = 2 To las
Private Sub CommandButton1_Click() Dim i As Long Dim namestr As String, othername As String Dim myValue As Integer Dim lastRow As Long
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow
If Range("F" & i).Value >= 4 And Range("F" & i).Value <= 6 Then
Select Case Range("F" & i).Value
Case 4
namestr = "取4个数的平均值.xlsm"
Case 5
namestr = "取5个数的平均值.xlsm"
Case 6
namestr = "取6个数的平均值.xlsm"
End Select
othername = Range("A" & i).Value
myValue = Range("D" & i).Value
Call userinit(namestr, othername, myValue)
End If
Next i
End Sub
Sub userinit(str As String, othersrt As String, addtime As Integer) Dim otherWorkbook As Workbook Dim otherWorksheet As Worksheet
Set otherWorkbook = Workbooks.Open("E:\检测设备\力学\VBA测试\" & str)
Set otherWorksheet = otherWorkbook.Worksheets("Sheet1")
otherWorksheet.Range("D14").Value = otherWorksheet.Range("J7").Value + addtime
Application.Run("'" & otherWorkbook.Name & "'!首页.CommandButton2_Click")
otherWorkbook.Close False
End Sub
注释:
- 去掉了不必要的注释和不使用的代码。
- 将整个循环改成了一个条件语句,减少了重复代码。
- 使用 Select Case 语句代替多个 If 语句,使代码更简洁。
- 去掉了不必要的变量声明。
- 将其他 Excel 文件的打开和关闭操作放在了 userinit 过程中,使代码更简洁。
- 在 userinit 过程中直接调用了另一个文件中的按钮函数,避免了处理返回值的操作
原文地址: https://www.cveoy.top/t/topic/gtcF 著作权归作者所有。请勿转载和采集!