【VBA】【EXCEL】退据坐标数据向右逐列填充求所有点之间的距离

Sub CopyRowToColumn()
    On Error GoTo ErrorHandler  '添加错误处理
    
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False  '禁用事件处理
    
    Dim lastCol As Long
    Dim lastRow As Long
    Dim i As Long, colCount As Long
    Dim ws As Worksheet
    Dim formulaStr As String
    Dim dataArr() As Variant  '使用数组来处理数据
    
    Set ws = ThisWorkbook.Worksheets("03.Obj Geom - Point Coordinates")
    
    '获取F列的最后一行
    lastRow = ws.Range("F" & ws.Rows.Count).End(xlUp).Row
    
    With ws
        '计算需要生成的列数
        colCount = lastRow - 3
        lastCol = 6 + colCount
        
        '将F列数据读入数组
        dataArr = .Range(.Cells(4, 6), .Cells(lastRow, 6)).Value
        
        '设置第3行的值
        For i = 1 To colCount
            .Cells(3, i + 6).Value = dataArr(i, 1)
        Next i
        
        '每次处理50列,分批设置公式
        Dim batchSize As Long
        Dim currentCol As Long
        batchSize = 50
        
        For currentCol = 7 To lastCol Step batchSize
            Dim endCol As Long
            endCol = Application.Min(currentCol + batchSize - 1, lastCol)
            
            '为这一批列设置公式
            For i = currentCol To endCol
                Dim colAddr As String
                colAddr = .Cells(3, i).Value
                
                formulaStr = "=IFERROR(ROUND(SQRT(((VLOOKUP(""" & colAddr & """,$A$1:$D$" & lastRow & ",2,FALSE)-" & _
                            "VLOOKUP($F{row},$A$1:$D$" & lastRow & ",2,FALSE))^2+" & _
                            "(VLOOKUP(""" & colAddr & """,$A$1:$D$" & lastRow & ",3,FALSE)-" & _
                            "VLOOKUP($F{row},$A$1:$D$" & lastRow & ",3,FALSE))^2))*1000,0),"""")"
                
                .Cells(4, i).Formula = Replace(formulaStr, "{row}", "4")
                
                If lastRow > 4 Then
                    .Cells(4, i).AutoFill _
                        Destination:=.Range(.Cells(4, i), .Cells(lastRow, i)), _
                        Type:=xlFillDefault
                End If
                
                '每10列清理一次剪贴板和内存
                If i Mod 10 = 0 Then
                    Application.CutCopyMode = False
                    DoEvents
                End If
            Next i
        Next currentCol
    End With
    
CleanExit:
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.CutCopyMode = False
    MsgBox "操作完成!", vbInformation
    Exit Sub

ErrorHandler:
    MsgBox "发生错误: " & Err.Description, vbCritical
    Resume CleanExit
End Sub

在这里插入图片描述

流程图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hmywillstronger

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值