我正在 excel 中创建一个仪表板,但是我想知道是否有更好的编码方式而不是这种方式。我想模块化它而不是这样做以使其更整洁。
Private Sub Afford()
If af.Value = True Then
af = afr.Value
Sheet1.Cells(35, "C").Value = Sheet1.Cells(57, "C").Value
Sheet1.Cells(35, "D").Value = WorksheetFunction.Round((Sheet1.Cells(35, "D").Value * 1.3), 0)
Sheet1.Cells(35, "E").Value = WorksheetFunction.Round((Sheet1.Cells(35, "E").Value * 1.02), 0)
Sheet1.Cells(35, "F").Value = WorksheetFunction.Round((Sheet1.Cells(35, "F").Value * 1.9), 0)
Sheet1.Cells(35, "G").Value = WorksheetFunction.Round((Sheet1.Cells(35, "G").Value * 1.9), 0)
Sheet1.Cells(35, "H").Value = WorksheetFunction.Round((Sheet1.Cells(35, "H").Value * 1.5), 0)
Run Code Online (Sandbox Code Playgroud)
好吧,纯粹基于您的这段特定代码,您可以尝试以下几行:
Option Explicit
Sub Sample()
Dim rng As Range
Dim x As Long
Dim arr As Variant
With Sheet1
'Input static values
.Cells(35, "C").Value = .[C57]
'Prepare for dynamic values
Set rng = .Range("D35:H35")
arr = Array(1.3, 1.02, 1.9, 1.9, 1.5)
'Insert dynamic values
For x = 1 To rng.Cells.Count
rng.Cells(1).Value = WorksheetFunction.Round(rng.Cells(1).Value * arr(x - 1), 0)
Next x
End With
End Sub
Run Code Online (Sandbox Code Playgroud)
或者,如果您的连接字符串不会超过 255 个字符:
Sub Sample()
Dim str As String
With Sheet1
'Input static values
.Cells(35, "C").Value = .[C57]
'Prepare for dynamic values
str = "{1.3,1.02,1.9,1.9,1.5}"
'Insert dynamic values
.Range("D35:H35").Value = .Evaluate("D35:H35*" & str)
End With
End Sub
Run Code Online (Sandbox Code Playgroud)