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



>上下文:我正在使用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

提前感谢!

附言我知道可能有一个选项可以将 R 图导出到 Excel 中,但我更感兴趣的是尝试弄清楚如何解释"with"函数结构。

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

do

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

而不是

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

最新更新