Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 如何更好地编写代码,使其看起来更整洁VBA_Excel_Vba - Fatal编程技术网

Excel 如何更好地编写代码,使其看起来更整洁VBA

Excel 如何更好地编写代码,使其看起来更整洁VBA,excel,vba,Excel,Vba,我正试图找出如何更好地编写代码。我试图使我的代码更整洁,但我就是不知道如何做到这一点 Private Sub Test() 'md = 30 ' 'If mbi.Value = False Then ' ' Sheet1.Cells(14, "C").Value = Sheet1.Cells(36, "t").Value * md * N1.Value ' Sheet1.Cells(14, "D").Value = Sheet1.Cells(36, "u").Val

我正试图找出如何更好地编写代码。我试图使我的代码更整洁,但我就是不知道如何做到这一点

   Private Sub Test()
    'md = 30

'
'If mbi.Value = False Then
'

'    Sheet1.Cells(14, "C").Value = Sheet1.Cells(36, "t").Value * md * N1.Value
'    Sheet1.Cells(14, "D").Value = Sheet1.Cells(36, "u").Value * md * N1.Value
'    Sheet1.Cells(14, "E").Value = Sheet1.Cells(36, "v").Value * md * N1.Value
'    Sheet1.Cells(14, "F").Value = Sheet1.Cells(36, "w").Value * md * N1.Value
'    Sheet1.Cells(14, "G").Value = Sheet1.Cells(36, "x").Value * md * N1.Value
这是我尝试过的,但我一直有错误

Private Sub test() 
md = 30


If Sheet1.mbi.Value = True Then 
With Sheet1
Dim rng As Range
Dim rng2 As Range
Dim x As Long
Set rng = .Range("C14:G14")
Set rng2 = .Range("t36:x36")

For x = 1 To rng.Cells.Count


    rng.Cells(1).Value = (rng2.Cells(1).Value * md * Sheet1.N1.Value)

End With
End If
End Sub

由于缺少
Next
,当前代码无法编译。要编写一段更整洁的代码,它可能看起来像:

Sub test()

Dim x As Long, md As Long: md = 30
Dim rng As Range, rng2 As Range

With Sheet1
    If .mbi.Value = True Then
        Set rng = .Range("C14:G14")
        Set rng2 = .Range("T36:X36")
        For x = 1 To rng.Cells.Count
            rng.Cells(x).Value = (rng2.Cells(x).Value * md * .N1.Value)
        Next x
    End If
End With

End Sub

注意:我还编辑了您的
rng.Cells(1.Value=(rng2.Cells(1.Value*md*Sheet1.N1.Value)
,因为我认为您希望实际使用
x
变量

首先没有
Next
,而且您从未使用
x
变量。这是指答案吗?你的标题有点误导人,因为你当前的代码一开始无法编译。@Jvdv在我使用了下一个“它起作用的家伙”后,你解决了它,我仍然认为你需要在代码中使用
x
)还有什么是
mbi
?你想用
Sheet1.N1.Value
实现什么?@SiddharthRout,我也在想同样的事情。