簡體   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