VBA使用公式在多张纸上填充单元格

时间:2018-04-15 07:01:41

标签: vba excel-vba loops for-loop excel-formula

我试图为每个工作簿中的每个单元格设置公式。我需要在2个不同的细胞范围内分配2个公式。我在Variant中定义了strFormula 1和2。

对于公式1,我希望分发到A列到AJ的单元格

对于公式2,我希望分配到AK列下的细胞到AR

运行循环后收到以下错误,定义strFormulas(2)时出现语法错误。希望能帮助解决这些问题。

谢谢!

  

运行时错误1004,应用程序定义或对象定义错误

rdd = sc.parallelize([1,2,3, 0])

def try_and_return(x, number_of_trys = 5):
    try_number = 0;
    return_value = None;

    while (try_number < number_of_trys):
        try:
            return_value = 1.0/x
            break
        except ZeroDivisionError:
            try_number += 1
    return return_value


print rdd.map(lambda x: try_and_return(x)).collect()

3 个答案:

答案 0 :(得分:4)

带引号的字符串中的引号需要加倍。替换为""的是文字(,),因此您不需要""""S是ascii 83。

strFormulas(1) = "=IF(ISBLANK('Sheet 1'!A4),"""",'Sheet 1'!B4)"
strFormulas(1) = "=IF(ISBLANK('Sheet 1'!A4), text(,), 'Sheet 1'!B4)"

strFormulas(2) = "=IF('Sheet 2'!N1838=""S"",""S"","""")"
strFormulas(2) = "=IF('Sheet 2'!N1838=char(83), char(83), text(,))"

答案 1 :(得分:2)

1)加倍你的&#34;&#34;。正如@Jeeped所说。

2)但要小心。这取决于您的纸张的订购,例如如果工作表1不是第一张工作表,您将最终在其中放置公式,引用工作表1;这可能是,也可能不是,你想要的。

Option Explicit

Sub AddFormulas()
    Dim w As Long
    Dim strFormulas(1 To 2) As Variant

    For w = 2 To ActiveWorkbook.Worksheets.Count
        With ActiveWorkbook.Worksheets(w) 'this targets by worksheet order so be careful
         strFormulas(1) = "=IF(ISBLANK('Sheet 1'!A4),"""",'Sheet 1'!B4)"
            strFormulas(2) = "=IF('Sheet 2'!N1838=""S"",""S"","""")"
            .Range("A2:AJ2").Formula = strFormulas(1)
            .Range("A2:AJ2000").FillDown
            .Range("AK2:AR2").Formula = strFormulas(2)
            .Range("AK2:AR2000").FillDown
        End With
    Next w
End Sub

答案 2 :(得分:1)

同时在所有工作表上填写公式的另一种方法

Option Explicit

Public Sub FillFormulasAcrossSheets()
    Dim i As Long, wsArr As Variant

    With ActiveWorkbook.Worksheets  'make array with all sheets
        ReDim wsArr(3 To .Count)
        For i = 3 To .Count
            wsArr(i) = i
        Next
    End With

    Application.ScreenUpdating = False

        Sheets(wsArr).Select
        'Or: ActiveWorkbook.Worksheets.Select       'Selects all
        'Or: Sheets(Array(2, 3, "Sheet5")).Select   'Specific sheets

        Range("A2:AJ2000").Select
                 Selection.Formula = "=IF('Sheet2'!N1838=""S"",""S"","""")"
        Range("AK2:AR2000").Select
                 Selection.Formula = "=IF('Sheet2'!N1838=char(83), char(83), text(,))"

        Range("A1").Activate
        Sheets(3).Select

    Application.ScreenUpdating = True
End Sub