簡體   English   中英

Excel VBA-復制公式並生成新工作表

[英]excel vba - copy formula and generate new sheets

如果我有一個名為“值”的工作表,其中只有1列包含單元格,例如:

ColumnA
---------
emp_id
emp_name
dept_id

然后是名為“ sql”的第二張工作表,其中包含兩列,其中包含單元格,例如:

ColumnA
--------
="select count(*) from tablex where "&a1&" is null;"
="select count(*) from tablex where length("&a1&") > 10;"

ColumnB
--------
Sheet for null
Sheet for length

什么VBA宏代碼(請注意,我需要在vba中使用它,因為我只想單擊一個按鈕即可生成工作表)我需要生成以下兩個輸出工作表(每個工作表只有一列):

    Sheet for null
-------------------
select count(*) from tablex where emp_id is null;
select count(*) from tablex where emp_name is null;
select count(*) from tablex where dept_id is null;


    Sheet for length
-------------------
select count(*) from tablex where length(emp_id) > 10;
select count(*) from tablex where length(emp_name) > 10;
select count(*) from tablex where length(dept_id) > 10;

我認為這將滿足您的要求。

我所做的一項更改是,在“ sql”表上,我將單元格內容更改為如下所示:

="select count(*) from tablex where variable is null;"

因此,我使用了“ variable ”而不是原來的“ &a1& ”,然后在代碼中用正確的emp_id,emp_name等值替換了該單詞。

    Sub GenerateSheets()
    Dim formulaRange As Range
    Dim formula As String
    Dim r As Range
    Dim destloc As Range
    Dim VariableRange As Range

    Set formulaRange = Worksheets("sql").Cells(1, 1)
    ' get each formula
    Do Until formulaRange.Value = ""
        For Each r In formulaRange.Rows
            ' for each formula found, create a new sheet and move it to end
            Worksheets.Add
            ActiveSheet.Name = r.Offset(0, 1).Value
            ActiveSheet.Move after:=Sheets(ActiveWorkbook.Sheets.Count)

            Set destloc = ActiveSheet.Cells(1, 1)
            Set VariableRange = Worksheets("values").Cells(1.1)
            ' Loop through all the variables
            Do Until VariableRange.Value = ""
                destloc.Value = Replace(formulaRange.Value, "variable", VariableRange.Value)

                Set VariableRange = VariableRange.Offset(1, 0)
                Set destloc = destloc.Offset(1, 0)
            Loop
        Next

        Set formulaRange = formulaRange.Offset(1, 0)
    Loop 
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM