繁体   English   中英

如何在 excel VBA 中编写毕达哥拉斯公式,就像我需要 select 列 A 和列 B 的所有值

[英]How to write Pythagoras formula in excel VBA, like I need to select all the values of column A and column B

Sub MS()    

Data = Sheets("Tabelle1").Select   
Rows("1:1").Select
Rows("11409:11409").Select

Dim bilder As Long
Dim n As Long
Dim d As Long
Dim t As Long

bilder = 64
n = 1    
d = 0
t = 0

'Dim i As Long   

'For i = 1 To lastrow

Range("a1:a" & Cells(Rows.Count, 1).End(xlUp).Row).Select

Range("b1:b" & Cells(Rows.Count, 1).End(xlUp).Row).Select

'Range("a1").Select

'Range("b1").Select

Range("a1,b1").Select

Do While ActiveCell.Value <> ""       
    Radius = Sqr(Range("A1").Value * Range("A1").Value + Range("B1").Value * Range("B1").Value)      
    ActiveCell.Offset(1, 1).Select 
Loop    

End Sub

我不确定你为什么要这样做(因为它可以用一个简单的公式在单元格中完成),但看看你问题中的代码残余,我们可以看到你想要什么达到。 这是我的做法:

Sub MS()

    Dim sht As Worksheet, StartRow As Long, LastRow As Long, OutputColumn As Long
    Dim SideA As Double, SideB As Double, SideC As Double
    
    With Worksheets("Tabelle1")
    
        'Set StartRow to the first row of your data ignoring headers
        StartRow = 2
        
        'Locate LastRow as last occupied cell in column A
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        
        'Set OutputColumn to 3
        OutputColumn = 3
        
        'Start loop
        For r = StartRow To LastRow
            SideA = .Cells(r, 1).Value
            SideB = .Cells(r, 2).Value
            SideC = Sqr(SideA * SideA + SideB * SideB)
            .Cells(r, OutputColumn).Value = SideC
        Next
        
    End With

End Sub

Output:

在此处输入图像描述

您不需要 select 范围来使用它。 您可能想查看如何避免在 Excel VBA 中使用 Select

在您的代码中,您没有将 output 写入任何单元格。 这里有两种方法可以帮助你实现你想要的。

非 VBA - 方式 1

将公式=SQRT(A1*A1+B1*B1)=SQRT(A1^2+B1^2)放入C1并向下拖动

VBA - 方式 2(无循环)

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long
    
    Set ws = Sheets("Tabelle1")
    
    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        
        With .Range("C1:C" & lRow)
            .Formula = "=SQRT(A1*A1+B1*B1)"
            .Value = .Value
        End With
    End With
End Sub

VBA - 方式 3(无循环)稍微复杂的方法。 解释可以在这里看到

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long
    
    Set ws = Sheets("Tabelle1")
    
    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        
        With .Range("C1:C" & lRow)
            .Value = Evaluate("index(SQRT((A1:A" & lRow & _
                              ")^2+(B1:B" & lRow & _
                              ")^2),)")

        End With
    End With
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM