4

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

提前致谢!

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

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

4

1 回答 1

4

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

代替

bar <- male$Selection()$Format()$Fill()
于 2013-10-04T10:34:38.283 回答