excel 使用变量作为工作表名称和范围VBA

jslywgbw  于 2022-12-14  发布在  其他
关注(0)|答案(2)|浏览(223)

嗨,我正在特灵使用函数作为generaly公式化,因为我可以。在这段代码中,我neet复制一些数据从一个工作表到另一个,我只得到调试...请帮助:
第一个
我尝试使用函数和变量将一些数据从一个工作表复制到另一个工作表,这样我就不必一遍又一遍地编写相同的代码

xe55xuns

xe55xuns1#

第一名

Range对象已将工作表作为父级包含。

Sub fCopyPasteValues(sourceSheet As Worksheet, targetSheet As Worksheet, sourceRange As Range, targetRange As Range)
    
        sourceRange.Select   '<-------------- THIS is where i get the Error, saying method or dataobjet not found! refering to sourceRange

        Range(Selection, Selection.End(xlDown).End(xlToRight)).Select
        Selection.Copy
        targetRange.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False
        Application.CutCopyMode = False
        targetRange.NumberFormat = "m/d/yyyy"
    
End Sub
rqqzpn5f

rqqzpn5f2#

第二名

或者,一种更简洁的方式来完成函数所做的一切。
此外,我将其更改为函数,并使其更加稳定:

Public Function fCopyVerfügbarkeitenData()

    Dim sourceRange As Range
    Dim targetRange As Range
    Dim sourceSheet As Worksheet
    Dim targetSheet As Worksheet
    
    Set sourceRange = Sheets("sheet1").Range("A4")
    Set targetRange = Sheets("sheet1").Range("A2")
    Set sourceSheet = Sheets("Verfügbarkeit_Daten")
    Set targetSheet = Sheets("Verfügbarkeiten")
    
    
    sourceSheet.Visible = True
    sourceSheet.Activate
    Call Tabelle18.refreshVerfuegbarkeiten
    
    fCopyPasteValues sourceRange, targetRange
    sourceSheet.Visible = False
                    
End Function

Function fCopyPasteValues(sourceRange As Range, targetRange As Range)
        
        ' Width and Height
        Dim W As Long
        Dim H As Long
        
        ' Find Outer Bounds
        H = sourceRange.End(xlDown).Row - sourceRange.Row + 1
        W = sourceRange.End(xlToRight).Column - sourceRange.Column + 1
        
        ' Error handing in case region is only 1 cell wide or high
        If H > 100000 Then H = 1
        If W > 100000 Then W = 1
        
        ' Copy and reformat Action
        targetRange.Resize(H, W).Value = sourceRange.Resize(H, W).Value
        targetRange.NumberFormat = "m/d/yyyy"
        
End Function

相关问题