如何通过RDCOMClient将VBA“with”函数结构解释为R代码?

时间:2013-10-04 10:24:03

标签: r excel vba excel-vba rdcomclient

上下文:我正在使用R进行一些数据操作,然后导出到Excel并创建一个条形图。

问题:到目前为止,记录Excel VBA宏然后通过RDCOMClient包将其转换为R代码非常容易。但是我不知道如何解释VBA“with”函数结构。

问题:我想将以下Excel VBA代码翻译成R代码(特别是使用RDCOMClient包):

' Activate barchart
ActiveSheet.ChartObjects("Chart 1").Activate

' Select the Male data column
ActiveChart.SeriesCollection(1).Select

' Change the colour of the Male bars in the barchart
With Selection.Format.Fill
    .Visible = msoTrue
    .ForeColor.ObjectThemeColor = msoThemeColorAccent1
    .ForeColor.TintAndShade = 0
    .ForeColor.Brightness = 0
    .Solid
End With

可重现代码:以下R代码将使用条形图设置excel工作表

# Load package and helper functions - see http://www.omegahat.org/RDCOMClient
require(RDCOMClient)
source("http://www.omegahat.org/RDCOMClient/examples/excelUtils.R")

# Create Excel application
xls <- COMCreate("Excel.Application")

# Make Excel workbook visible to user
xls[["Visible"]] <- TRUE

# Add a worksheet to the workbook
wb = xls[["Workbooks"]]$Add(1)

# Add data.frame to worksheet (Hishest Qualification of Job Applicants by Sex)
df <- data.frame(Degree=c("BSc", "MSc", "PhD"), Male=c(322, 107, 39), Female=c(251, 128, 25))
exportDataFrame(df, at = wb$ActiveSheet()$Range("A1"))

# Add Chart
chart.display.range <- wb$ActiveSheet()$Range("E2:M20")
wb$ActiveSheet()$Range("A1:C4")$Select()
wb$ActiveSheet()$Shapes()$AddChart(Top = chart.display.range$Top(), 
                                   Left = chart.display.range$Left(), 
                                   Height = chart.display.range$Height(), 
                                   Width = chart.display.range$Width())$Select()

到目前为止我做了什么: VBA代码的前两行很容易翻译成R:

# Activate chart
wb$ActiveSheet()$ChartObjects("Chart 1")$Activate()

# Select the Male data column
male <- wb$ActiveChart()$SeriesCollection(1)
male$Select()

然后是with结构

# bar colour to be changed (this is a guess)
bar <- male$Selection()$Format()$Fill()

会导致以下错误:

#Error in .COM(x, name, ...) : 
# Cannot locate 0 name(s) Selection in COM object (status = -2147352570)

我不应该使用我所说的“选择”?我不知道从哪里开始,但我认为一旦我修正了上面的错误,我会做类似以下的事情:

bar[["Visible"]] = 1
bar[["ForeColor"]][["ObjectThemeColor"]] = 5
bar[["ForeColor"]][["TintAndShade"]] = 0
bar[["ForeColor"]][["Brightness"]] = 0

提前致谢!

P.S。我知道可能有一个选项可以将R图输出到Excel中,但我更想知道如何解释“with”函数结构。

P.P.S我正在使用Windows 7 x64,x86_64-w64-mingw32 / x64(64位),R 3.0.1,RDCOMClient_0.93-0.1

1 个答案:

答案 0 :(得分:3)

待办事项

bar <- male$Format()$Fill()

而不是

bar <- male$Selection()$Format()$Fill()